Unmanaged code returning a string by reference into a struct.

May 18 2007 10:42 AM

 

Hi,
I have a problem trying to return some values by reference from unmanaged code.
 
This is the unmanaged code struct definition:

 

typedef struct

      {

LVBoolean status;  // marshaled as boolean type

long code;

LStrHandle source;  // marshaled as string type

       } TD1;

 

The function being called from ANSI C has this signature:

 

void __stdcall DSATSInitializeInstrument(char DSAResourceName[], TD1 *errorOut);  //note we are using a pointer to errorOut.

 


I'm trying to use the unmanaged function with the DllImport directive,

 

[DllImport("AudioMeasureVIs.dll", EntryPoint = "DSATSInitializeInstrument", CallingConvention = CallingConvention.StdCall)]
public static extern void Open(StringBuilder DSAResourceName, ref TD1 errorOut);


And this is the actual function call (signature) on C#:


//Class TD1 declaration
PInvoke.TD1 errorOut = new PInvoke.TD1(); 

//errorOut is sent by reference...

PInvoke.Open(nombre, ref errorOut);

errorOut should have the Error information upon return of the function


//Class definition

public class PInvoke

{

public class TD1

{

public ushort status;

public long code;

public string source;

}

 

[DllImport("AudioMeasureVIs.dll", EntryPoint = "DSATSInitializeInstrument", CallingConvention = CallingConvention.StdCall)]

public static extern void Open(string DSAResourceName, ref TD1 errorOut);

}

I’m using a class instead of the struct because structs are value types and classes are reference types.

The function is called correctly, the problem I have is that when it returns I get the following error:

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

It seems that I cannot return a value by reference into a struct or a class from unmanaged code. Does anyone know if there is a way this can be done?

Any help is appreciated.

Joel