C# using C dll, making pointer to struct
Hi. I need to basically have an equivalent C# struct to my C struct. I need to make a pointer to it. This is the relevant code:
C code:
#if defined(WIN32)
# define DLL_EXPORT __declspec(dllexport)
#else
# define DLL_EXPORT /**/
#endif
#ifdef __cplusplus
extern "C" {
#endif
struct vector
{
uint elem_count; /* number of items in the vector */
uint size; /* size of the vector */
uint elem_size; /* element size */
int (*cmp)(const void *, const void *);
void *table;
};
typedef struct vector VECTOR;
#define CSTATS VECTOR
//function definition:
DLL_EXPORT CSTATS *screate(); // returns CSTATS pointer
...
#ifdef __cplusplus
}
#endif
C# code:
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
unsafe public delegate int cmp(IntPtr a, IntPtr b);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe public struct VECTOR
{
public uint elem_count;
public uint size;
public uint elem_size;
[MarshalAs(UnmanagedType.FunctionPtr)]
public cmp cp; //C-func: public int (*cmp)(const void *, const void *);
public IntPtr table;
}
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
unsafe public delegate VECTOR screate();
[DllImport("myTest.dll", EntryPoint = "screate", ExactSpelling = true)]
public static extern screate scrt();
Now, here is the problem. The C code I want to emulate in C# is this:
CSTATS *st;
st = screate();
In C#, I tried:
VECTOR* st = screate();
VECTOR* st = scrt();
and so on...
The error I get is:
error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myDll.VECTOR')
So I am looking for help. What is the equivalent C# code that I need, in order to achieve "CSTATS *st; st = screate();" in C?
Thank you for any help.
ZPosted Nov 16, 2007, 4:02 PM
AlanPosted Nov 16, 2007, 3:36 PM
I've seen this problem many times before on here but I'm not sure what the reason is for it, unless it's something to do with the browser you're using.
Something that always works for me is to type or paste everything into notepad first, before I post it. I use IE7 by the way.
Anyway, on to your coding problem :)
The difficulty seems to be that your VECTOR struct contains a delegate (i.e. a reference type in C#) and is not therefore regarded as an unmanaged type, which precludes you from declaring a pointer to it.
I'd try changing VECTOR to a class so that the variable 'st' will automatically contain a reference to a VECTOR object. You can then just do:
VECTOR st = scrt();
Incidentally, there's no need to use 'unsafe' in C# unless you're actually using explicit pointers which doesn't appear to be the case from the code you've posted.
ZPosted Nov 16, 2007, 1:56 PM