Yet another one of my P/Invoke questions! I have this C function:
int _ei_x_new(ei_x_buff* x);
Essentially, it initializes a new buffer struct. In C#, I have this:
[DllImport(EIDLL, EntryPoint = "_ei_x_new")]
public static extern int ei_x_new(out ei_x_buff x);
ei_x_buff
is pretty simple:
typedef struct ei_x_buff_TAG {
char* buff;
int buffsz;
int index;
} ei_x_buff;
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ei_x_buff {
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string buff;
public int buffsz;
public int index;
}
But when I do this:
ei_x_buff buffer;
Ei.ei_x_new(out buffer);
I get an AccessViolationException:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Do I need to alloc some memory or something? It's such a simple piece of code that I can't see any glaring problems with it.
EDIT: Native code for _ei_x_new
:
// In my wrapper library
DLL_EXPORT int _ei_x_new(ei_x_buff* x) {
return ei_x_new(x);
}
// In external library being wrapped
int ei_x_extra = 100;
int ei_x_new(ei_x_buff* x)
{
x->buff = malloc(ei_x_extra);
x->buffsz = ei_x_extra;
x->index = 0;
return x->buff != NULL ? 0 : -1;
}