从C#传递字符指针C ++

问题描述:

可能重复:结果
从C#传递字符指针,以C ++函数

我有这种类型的问题:

我有这个签名的C ++函数:

I have a c++ function with this signature:

int myfunction ( char* Buffer, int * rotation)

buffer参数必须用空格字符(0x20的十六进制)

The buffer parameter must be filled with space chars ( 0x20 hex )

在C ++中我能解决简单地做这样的问题:

In C++ i can solve the problem simply doing this:

char* buffer = (char *)malloc(256);
memset(buffer,0x20,256);
res = myfunction (buffer, rotation);



我试图调用从C#此功能。

I'm trying to call this function from C#.

这是我的p / Invoke声明:

This is my p/invoke declaration:

[DllImport("mydll.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern unsafe int myfunction (StringBuilder Buffer, int* RotDegree);

在我的C#类我试图做到这一点:

In my C# class i've tried to do this:

StringBuilder buffer = new StringBuilder(256);
buffer.Append(' ', 256);
...
myfunction(buffer, rotation);



但它不工作....

but it doesn't work....

任何人都可以帮我吗?

感谢。

您的p / Invoke看起来不完全正确。它应该(大概)使用 CDECL 调用约定。你不应该使用 SetLastError 。 。而且也没有必要不安全的代码

Your p/invoke doesn't look quite right. It should (presumably) use the Cdecl calling convention. You should not use SetLastError. And there's no need for unsafe code.

我会写这样的:

[DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int myfunction(StringBuilder Buffer, ref int RotDegree);



然后调用它是这样的:

Then call it like this:

StringBuilder buffer = new StringBuilder(new String(' ', 256));
int rotation = ...;
int retVal = myfunction(buffer, ref rotation);



我没有指定字符集安思是默认的。