MarshalAs and DllImport



Hi ,
I'm wiring an application that need to use a DLL writed in C .
I have some difficult to call the following function :

int MyUnsafeFunc( char*[] file_arr);

From C all work fine , like follow :

void MyFuncCall ( void )
{
char *filename_array[3] = {
"filename_1.txt",
"filename_2.txt",
NULL
};

int err = MyUnsafeFunc(filename_array);
}

From C# I try 2 differeny solution , but none of this work fine , and for
Both mode of calling from C# , I have following exception :

"Attempted to read or write protected memory. This is often an indication
that other memory is corrupt."


------------------------------------------------------
Try Calling from C# ( mode 1 ) :

void MyFuncCall ( )
{
char*[] pFiles = new char*[3];

String f0 = "filename_1.txt";
String f1 = "filename_2.txt";
pFiles[0] = (char*)Marshal.StringToBSTR(f0).ToPointer();
pFiles[1] = (char*)Marshal.StringToBSTR(f1).ToPointer();
pFiles[2] = (char*)null;

int ret = MyUnsafeFunc( pFiles );
}

.....

[DllImport("MyUnsafeDll.dll")]
unsafe public static extern int MyUnsafeFunc( char*[] file_arr );

------------------------------------------------------
Try Calling from C# ( mode 2 ) :

void MyFuncCall ( )
{
String[] par = { "filename_1.txt", "filename_2.txt", null };
int ret = MyUnsafeFunc(ref par);
}

[DllImport("MyUnsafeDll.dll")]
public static extern int MyUnsafeFunc(
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] ref
String[] file_arr);

------------------------------------------------------

Who can give me a good advise to solve this problem ?

Thank You
.


Loading