gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:01:46 33 4
gpt4 key购买 nike

我在从 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com