void ** 处理 P/Invoke

Bri*_*ian 2 c# pinvoke

我正在使用来自第 3 方供应商的 C API DLL。我遇到的问题是,我似乎找不到用于编组以下 C 代码的好模板:

API_Open( void ** handle );
API_Close( void * handle );
Run Code Online (Sandbox Code Playgroud)

调用被简化了,但句柄是一个 void *,它(在 C 中)API_Open作为 &handle传入调用,然后API_Close作为句柄传入。

我尝试在 C# 中做同样的事情,但无法弄清楚如何正确处理 Marshal。我的 C# 版本(最新尝试)是:

[DllImport("External.dll",EntryPoint="API_Open")]
public static extern int API_Open( out IntPtr handle );
[DllImport("External.dll",EntryPoint="API_Close")]
public static extern int API_Close( IntPtr handle );

public static int Wrapper_API_Open( ref Int32 handle )
{
    int rc = SUCCESS;

    // Get a 32bit region to act as our void**
    IntPtr voidptrptr = Marshal.AllocHGlobal(sizeof(Int32));

    // Call our function.  
    rc = API_Open(out voidptrptr);

    // In theory, the value that voidptrptr points to should be the 
    // RAM address of our handle.
    handle = Marshal.ReadInt32( Marshal.ReadIntPtr(voidptrptr) );

    return rc;
}

public static int Wrapper_API_Close(ref Int32 handle)
{
    int rc = SUCCESS;

    // Get a 32bit region to act as our void *
    IntPtr voidptr = Marshal.AllocHGlobal(sizeof(Int32));

    // Write the handle into it.
    Marshal.WriteInt32(voidptr,handle);

    // Call our function.
    rc = API_Close(voidptr);

    return rc;
}


public void SomeRandomDrivingFunction()
{
    .
    .
    .
    Int32 handle;
    Wrapper_API_Open( ref handle );
    .
    .
    .
    Wrapper_API_Close( ref handle );
    .
    .
    .
}
Run Code Online (Sandbox Code Playgroud)

当我调用 API_Close 时,API 返回码始终为 INVALID_DEVICE_OBJECT。有什么想法吗?我认为这会非常简单,但是我无法将头放在函数调用的 void** 和 void* 部分上。

谢谢

Dav*_*nan 5

你似乎把这个问题复杂化了。我不知道你为什么要引入Int32句柄,因为它们确实需要是指针大小的。你应该使用IntPtr.

API_Open接受其中返回的句柄的变量的地址。调用者分配该变量并将其传递给填充变量的被调用者。C 函数可能如下所示:

int API_Open(void **handle)
{
    *handle = InternalCreateHandle();
    return CODE_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

你会在 C 中这样称呼它:

void *handle;
int retval = API_Open(&handle);
if (retval != CODE_SUCCESS)
    // handle error
// go one and use handle
Run Code Online (Sandbox Code Playgroud)

转换为 C#,void*映射到IntPtr,并且使用双指针只是为了避开 C 仅支持按值传递这一事实。在 C# 中,您将使用按引用传递。

因为API_Close它更简单,因为我们是按值传递句柄:

int API_Close(void *handle)
{
    InternalCloseHandle(handle);
    return CODE_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

调用代码很简单:

int retval = API_Close(handle);
if (retval != CODE_SUCCESS)
    // handle error
Run Code Online (Sandbox Code Playgroud)

因此,C# 包装函数应该是:

public static int Wrapper_API_Open(out IntPtr handle)
{
    return API_Open(out handle);
}

public static int Wrapper_API_Close(IntPtr handle)
{
    return API_Close(handle);
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,这些包装方法看起来确实有些毫无意义!