views:

184

answers:

1

Hi people, this is my first post here!

I'm trying to make a windows forms program using C# which will use a precompiled C library. It will access a smart card and provide output from it. For the library, I have a .dll, .lib and .h and no source. In the .h file there are several structs defined. Most interesting functions of the .dll expect pointers to allocated structs as arguments. I've been calling functions inside the .dll like this: For example function

EID_API int WINAPI EidStartup(int nApiVersion);

would be called like this

[DllImport("CelikApi.dll")]//the name of the .dll
public static extern int EidStartup(int nApiVersion);

Now my problem is that I can't find equivalent of C's pointers which point to dynamically allocated structures in memory in C#, so I don't know what to pass as argument to functions which take C pointers.

I don't have much experience in C#, but to me its use looked as the easiest way of making the program I need. I tried with C++, but Visual Studio 2010 doesn't have IntelliSense for C++/CLR. If you can point me to something better, feel free to do so.

+1  A: 

You can do something like

    [DllImport("Operations.dll")]
    public static extern void Operation(
        [MarshalAs(UnmanagedType.LPArray)]ushort[] inData, 
        int inSize1, int inSize2,
        [MarshalAs(UnmanagedType.LPArray)]int[] outCoords,
        ref int outCoordsSize);

That code will take a dynamically allocated array of unsigned shorts (ushort in C#), as well as multiple size parameters (inSize1 and inSize2), and place results in the outCoords array of size outCoordsSize.

Your C code cannot allocate memory and expect C# to play nice with it; C# should allocate all memory that your C code plays with. In the above case, you could put the size of the outCoords array in outCoordsSize, and then replace the value of outCoordsSize with the amount of memory you actually used (which cannot exceed the amount of memory you originally allocated without an exception).

mmr