0

我有一个问题 PInvoking a native function from c++ ...我已经 PInvoked 所有其他本机函数没有问题(参数是非常简单的转换)。下面是 c++ 原型及其在 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) 这是 PInvoke 这个 API 的正确方法吗?2)我怎样才能得到我有255作为参数的ptr的大小?

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

谢谢

4

1 回答 1

1
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); 

} 
于 2012-06-30T01:29:22.967 回答