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

如何将int/double/string/int[]类型的参数从C#传递到本机C?,c#,c,pinvoke,native,managed,C#,C,Pinvoke,Native,Managed,可以这样做吗: [DllImport(DllName, CallingConvention = DllCallingConvention)] private static extern void SetFieldValue(string fieldName, int[] value, int count); [DllImport(DllName, CallingConvention = DllCallingConvention)] private static extern void SetF

可以这样做吗:

[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);
本机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
参数作为指向以null结尾的字符数组的指针进行编组。在这两种情况下,这都是您需要的。

您的问题是什么?我觉得你的代码没问题。我的问题是PInvoke臭名昭著,它会导致难以发现的bug。我正试图了解这些事情是如何最好/最安全地完成的。谢谢!这是我从未听说过的。因此,当这样做时,本机代码与我的问题相同?这看起来确实是一个很好的方法。最好包含一个使用值类型的重载,太容易忘记使用
ref
@HansPassant:谢谢,但我不明白:“最好包含一个使用值类型的重载,太容易忘记使用ref”。我理解托管端的重载,但我在问我的原生C代码是否正确。C-没有重载。