【问题标题】:Passing char pointer from C# to C++ [duplicate]将 char 指针从 C# 传递到 C++ [重复]
【发布时间】:2012-12-21 16:07:06
【问题描述】:

可能重复:
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# 课程中,我尝试过这样做:

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

但它不起作用....

谁能帮帮我?

谢谢。

【问题讨论】:

  • “但它不起作用”没有帮助。
  • 您甚至没有显示 p/invoke 声明!如果没有这样的基本信息,我们将无法为您提供帮助。
  • @FrancisP 这个问题不是那个问题的重复!

标签: c# pointers pinvoke


【解决方案1】:

您的 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 是默认值。

【讨论】:

    【解决方案2】:

    尝试通过引用传递rotation。您可能还需要编辑myfunction 的签名。请让我知道该方法是否有效。

    myfunction (buffer.ToString(), ref rotation);
    

    【讨论】:

      猜你喜欢
      • 2011-05-22
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2021-04-17
      • 2012-12-29
      • 1970-01-01
      • 2019-12-13
      相关资源
      最近更新 更多