C# 调用 API调用成功但是结果不对,请高手指教

hahawuwu 2005-05-10 10:22:07
C++编写的API
头文件为
extern "C"
{
__declspec(dllexport) char* PinJie(char* pA, char* pB);
}
CPP中的函数为,目的是连接连个字符串
char* PinJie(char* pA, char* pB)
{
int nA = strlen(pA);
int nB = strlen(pB);
int nOut = nA + nB;
char* pOut = new char [nOut + 1];
if(pOut != NULL)
{
memcpy(pOut, pA, nA);
memcpy(pOut + nA, pB, nB);
pOut[nOut] = 0;
}
return pOut;
}


我在C#中是这样调用的

using System.Runtime.InteropServices;

namespace ImportDll
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
[DllImport("PinJie.dll",ExactSpelling = true,CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)]
unsafe public static extern char* PinJie(char* a, char* b);

private void Page_Load(object sender, System.EventArgs e)
{
unsafe
{
char str_a = '1';
char str_b = '2';
char* chr_a = &str_a;
char* chr_b = &str_b;

Page.Response.Write(*PinJie(chr_a,chr_b));
}
}
}
}

我想返回的结果是12也就是字符串连接,但是现在返回的东西比较怪异不知道为什么在哪里,请高手指教
...全文
155 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
beijingbeerman 2005-08-14
  • 打赏
  • 举报
回复
试试这个代码:
[DllImport("PinJieDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern string PinJie(string a, string b);
private void Page_Load(object sender, System.EventArgs e)
{
Page.Response.Write(PinJie("1", "2"))
}
yuqingjiang 2005-05-10
  • 打赏
  • 举报
回复
对不起我的回答太简单了。看你程序中的调用,应该不会受限。
跨平台调用最要注意的就是参数的大小,
你用 sizeof看一下char的长度,比较一下在你dll 中sizeof(str_a)的长度可能会出现16位和8位的区别。这个时候你就要转换byte在C#里是8位的。
另外,尽量使用标准跨平台调用。
[DllImport("PinJie.dll",CharSet=CharSet.Auto]
public static extern IntPtr PinJie(IntPtr a, IntPtr b);

char aa = '1';
char bb = '2';

IntPtr ca = IntPtr.Zero;
Marshal.WriteInt16(pa,aa);//Marshal.WriteByte(pa,aa);

hahawuwu 2005-05-10
  • 打赏
  • 举报
回复
谢谢sayo我的问题解决了!
sayo 2005-05-10
  • 打赏
  • 举报
回复
上面的PinJieDll.dll应改为PinJie.dll,不好意思
sayo 2005-05-10
  • 打赏
  • 举报
回复
尝试使用如下代码:
[DllImport("PinJieDll.dll", ExactSpelling = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern string PinJie(string a, string b);
private void Page_Load(object sender, System.EventArgs e)
{
Page.Response.Write(PinJie("1", "2"))
}
hahawuwu 2005-05-10
  • 打赏
  • 举报
回复
再顶一下吧,受不了了,都弄了一天了
1:27916432
2:27916428
㈱:207490192
这个是我执行的结果,后面的数是地址
qiezic 2005-05-10
  • 打赏
  • 举报
回复
mark
hahawuwu 2005-05-10
  • 打赏
  • 举报
回复
那也就是说我这样做不可以吗?
yuqingjiang 2005-05-10
  • 打赏
  • 举报
回复
WebForm中的跨平台调用受限制
hahawuwu 2005-05-10
  • 打赏
  • 举报
回复
自己顶一下,高手出招吧

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧