c# - 将字符指针从 C# 传递到 C++

标签 c# pointers pinvoke

<分区>

Possible Duplicate:
Passing char pointer from C# to c++ function

我有这样的问题:

我有一个带有此签名的 C++ 函数:

int myfunction ( char* Buffer, int * rotation)

缓冲区参数必须用空格字符(0x20 hex)填充

在 C++ 中,我可以简单地解决这个问题:

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

我正在尝试从 C# 调用此函数。

这是我的 p/invoke 声明:

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

在我的 C# 类(class)中,我尝试这样做:

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

但它不起作用......

谁能帮帮我?

谢谢。

最佳答案

您的 p/invoke 看起来不太正确。它应该(大概)使用 Cdecl 调用约定。您不应使用 SetLastError。而且不需要不安全的代码。

我会这样写:

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

然后这样调用它:

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

我没有指定 CharSet,因为 Ansi 是默认值。

关于c# - 将字符指针从 C# 传递到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993396/

相关文章:

c# - web.config 转换从 web.template.xml 不工作

c - 将数据写入双向链表时发生访问冲突

c++ - 如何使指针指向二维数组的任意数组元素?

c# - 编码普通结构 : does C# copy them onto heap?

c# - 通过 OleDB 读取 Excel 文件时非空单元格中的 DBNull

c# - WCF 服务可以使用它自己的服务吗?

c# - 是否应该将此列表初始值设定项行为报告为 Visual Studio C# 编译器中的错误?

c - 3d 数组在引用两次后打印地址?

c# - 是否可以使用 "pure".NET 和*不*使用 p/invoke 重新启动 PC?

c# - C#获取磁盘簇大小--出现 'GetDiskFreeSpace'错误