In C code, the function is defined like:
INT WINAPI myFunction(LPCTSTR str1, LPCTSTR str2, INT iNumber,
LPSTRUCT *lpStruct);
*lpStruct is an array of pointers of a struct type:
typedef struct myStruct
{
CHAR m_s1[64];
UINT m_nS;
CHAR m_s2[8][64];
UINT m_nP;
CHAR m_s3[512];
} SomeStruct, *LPSTRUCT;
I need to call this external myFunction in C#, I defined SomeStruct as:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SomeStruct
{
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)]
public string m_s1;
public uint m_nS;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 512)]
public string m_s2;
public uint m_nP;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 512)]
public string m_s3;
}
myFunction as:
[DllImport("some.dll")]
public static extern int myFunction(
string str1,
string str2,
int iNumber,
IntPtr[] lpStruct);
I initialize IntPtr[] in C#:
IntPtr[] lpptr = new IntPtr[iNumber];
I know the struct array of pointer has iNumber elements.
There is no error to call this function (lpStruct[i] has number). But when I tried to Marshal the pointer to the struct using:
SomeStruct st = (SomeStruct )Marshal.PtrToStructure(lpStruct[i],
typeof(SomeStruct ));
I got error message: try to write read-only memory. I don’t know what’s wrong here. Is the external function definition in C# wrong or the definition of struct wrong, or both.
The question lacks important details, but I would expect that you need to allocate memory for each IntPtr in the array.
And obviously you should free the memory once you are done with it.