簡體   English   中英

如何將C#類型為int / double / string / int []的參數傳遞給本地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參數被編組為指向以null結尾的字符數組的指針。 在這兩種情況下,這都是您所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM