C#调用C++的DLL乱码, 函数原型是:char *fuc(char *a,char *b)
在C语言的标准库函数中,有strcat()函数,它的作用是连接两个字符串,原型如下:
char *strcat(char *strDestination, const char *strSource)
作用是:在 Dest 的后面接上 Src 指向的字符串,把两个字符串连接起来。
我自己实现了 my_strcat(char *dst, char *src)函数,代码如下:
extern "C"
{
__declspec(dllexport) char *my_strcat(char *dst, char *src)
{
char *old_pos = dst;
while (*dst)
{
dst++;
}
while (*dst++ = *src++)
{
;
}
return old_pos;
}
}
//导入刚刚生成的 DLL ,函数入口是 my_strcat ,调用方式是 cdecl ,字符集是 unicode
[DllImport("*.dll", EntryPoint = "my_strcat", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern string my_strcat(string a, string b);
//在点击事件中把文本框1中的字符串,文本框2中的字符串连接起来,然后把连接的字符串放在文本框3中。
textBox3.Text = my_strcat(textBox1.Text, textBox2.Text);
// 危险代码!!
int i = 0;
char src[] = "hello";
my_strcat(src, "buffer overflow");
printf("i=%x", i); //i=776f6c66
void my_str(char* dst, const char* src, int dst_length)
{
int offset = strnlen(dst, dst_length);
for(int i = offset; i < dst_length && *src; i++)
{
dst[i] = *src++;
}
}