如何将 int/double/string/int[] 类型的参数从 C# 传递给本机 C?

How to pass parameter that can be of type int/double/string/int[] from C# to native C?

可以这样吗:

本机 DLL:

void SetFieldValue(const char *Field, void *pValue, int Count)
{
    char *StrValue;
    int *IntArrayValue;
    if (!strcmp(Field, "StrField"))
    {
        StrValue = malloc((Count + 1) * sizeof(char)); 
        strcpy(StrValue, (char *)pValue);
        DoSomethingWithStringValue(StrValue);
        free(StrValue);
    }
    else if (!strcmp(Field, "IntArrayField"))
    {
        IntArrayValue = malloc(Count * sizeof(int)); 
        memcpy(IntArrayValue, pValue, Count);
        DoSomethingWithIntArrayValue(IntArrayValue);
        free(StrValue);
    }
    //... and so on
}

托管:

[DllImport(DllName, CallingConvention = DllCallingConvention)]
private static extern void SetFieldValue(string fieldName, IntPtr value, int count);


public void SetIntArray()
{
    int[] intArray = { 1, 2, 3 };
    SetFieldValue("IntArrayField", intArray, 3);
}


public void SetString()
{
    SetFieldValue("StrField", "SomeValue", 9);
}

//... and so on

一种方法是使用方法重载。在 C# 端,您将声明导入函数的多个版本。对于问题中的两个示例,如下所示:

[DllImport(DllName, CallingConvention = DllCallingConvention)]
private static extern void SetFieldValue(string fieldName, int[] value, int count);

[DllImport(DllName, CallingConvention = DllCallingConvention)]
private static extern void SetFieldValue(string fieldName, string value, int count);

这两个 p/invoke 函数链接到同一个非托管函数。对于第一个重载,value 参数被编组为指向数组第一个元素的指针。对于第二个重载,value 参数被编组为指向空终止字符数组的指针。在这两种情况下,这就是您所需要的。