Can it be done something like this:
Native 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
}
Managed:
[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
One way is to use method overloading. On the C# side you would declare multiple versions of the imported function. For the two examples in the question that would look like this:
[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);
These two p/invoke functions are linked to the same single unmanaged function. For the first overload, the value
argument is marshalled as a pointer to the first element of the array. For the second overload the value
argument is marshalled as a pointer to a null-terminated character array. In both cases that is what you need.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments