【发布时间】:2016-05-17 08:16:43
【问题描述】:
可以这样做吗:
本机 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
【问题讨论】:
-
你的问题是什么?你的代码在我看来没问题。
-
我的问题是 PInvoke 臭名昭著导致难以发现的错误。我正在尝试就如何最好/最安全地完成这类事情征求意见。
标签: c# c pinvoke native managed