将不同类型的 objects 传递给非托管函数

Passing different type of objects to unmanaged function

首先:如果标题有误,请见谅。我不确定如何命名我的问题。

在我的 C API 我有一个函数:

MYAPI_STATUS SetParam(void *hInst, unsigned long param, void *value);

此函数根据 param 类型接受不同类型的指针。像这样:

SetParam(hInst, 1, (void*)"somevalue");
int x = 55;
SetParam(hInst, 2, &x); 

我正在用 C# 编写 wrapper/binding,但遇到了问题。

[DllImport("myapi", CallingConvention = CallingConvention.Cdecl]
public static extern uint SetParam(IntPtr hInst, uint paramCode, IntPtr paramValue);

从 C 复制行为的最佳方法是什么?所以函数看起来像:

public static uint SetParam(IntPtr hInst, uint paramCode, ref object paramValue);

或者可能:

public static uint SetParam(IntPtr hInst, uint paramCode, object paramValue);

我通过手动编组解决了这个问题,首先检查 object 的类型,如果 objectstring 然后我使用 Marshal.StringToHGlobalAnsi 如果它是其他东西那么我编组基于不同的关于我需要的。

如果有人有任何更好的解决方案,请随时写:)

C编程中的*符号表示给参数by reference,所以这段代码不匹配:

public static uint SetParam(IntPtr hInst, uint paramCode, object paramValue);

因为它给出参数by value.

此代码与您想要的非常相似:

public static uint SetParam(IntPtr hInst, uint paramCode, ref object paramValue);

但是有一点不同。当您在参数前使用 ref 时,您必须在将其发送到方法之前对其进行初始化,但是通过使用 out ,您就没有传递它的限制。所以我认为最好的匹配是这段代码:

public static uint SetParam(IntPtr hInst, uint paramCode, out object paramValue);