c# - 要在 C# 中使用的 PInvoke C++ 函数

标签 c# c++ pinvoke marshalling

我在从 C++ 调用 native 函数时遇到问题...我已经毫无问题地调用了所有其他 native 函数(参数是非常简单的转换)。下面是c++原型(prototype)及其在c++中的用法:

DECL_FOOAPIDLL DWORD WINAPI FOO_Command(
VOID *Par,  //pointer to the parameter(s) needed by the command 
DWORD Len,  //length of Parameter in bytes
DWORD Id    //identification number of the command 
);

用法:

static DWORD DoSomething(WCHAR *str)
{
DWORD len = (wcslen(str)+1)*sizeof(WCHAR);
DWORD ret = FOO_Command((VOID *)str,len,FOOAPI_COMMAND_CLOSE);
return(ret);
}

我的 C# PInvoke:

[DllImport("FOO.dll")]
    static public extern uint FOO_Command(IntPtr par, uint len, uint id);

private void DoSomething()
{

    string text = "this is a test";
    IntPtr ptr = Marshal.StringToHGlobalUni(text);

    uint hr = FOO_Command(ptr,255, FOOAPI_COMMAND_CLOSE);

    Marshal.FreeHGlobal(ptr);

}

1) 这是调用此 API 的正确方法吗? 2) 如何获得参数为 255 的 ptr 的大小?

以上确实有效,但我是 PInvoke 和“本地”世界的新手...

谢谢

最佳答案

private void DoSomething() 
{ 

    string text = "this is a test"; 
    IntPtr ptr = Marshal.StringToHGlobalUni(text); 

    uint hr = FOO_Command(ptr, (text.Length + 1) * 2, FOOAPI_COMMAND_CLOSE); 

    Marshal.FreeHGlobal(ptr); 

} 

关于c# - 要在 C# 中使用的 PInvoke C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11267654/

相关文章:

c# - 应该抛出单元测试失败但 saga 处理程序代码确实抛出不可恢复的异常

c# - 在 ListView 中显示内容选择器属性 - Umbraco v 7.4

c++ - 未创建 Keil uVision5 .axf 文件

c++ - macOS 上使用 cpptools 1.71.1+ : When trying to compile code in C++, 的 VS Code "-std=gnu++14"出现在所有标志之前。怎么删除呢?

.net - P/Invoke 和非托管 DLL 状态

.net - 我们真的需要捕获 P/Invoke 方法的异常吗?

c# - 编码包含 C 字符串的结构

c# - 介于另一列的值之间

c++ - 从书中复制的代码无法编译。已弃用或打字错误?

c# - AWS SQS,如何计算消息属性的 MD5 消息摘要