How to map a C array to C#?

谁都会走 提交于 2021-02-10 02:32:18

问题


My question has to do with trying to call a function written in C from C#. I've looked in a header file that came with the C library to understand the functions as they exist in the C dll. Here's what I see:

C code (for a function called "LocGetLocations"):

typedef enum {
    eLocNoError,
    eLocInvalidCriteria,
    eLocNoMatch, 
    eLocNoMoreLocations,
    eLocConnectionError, 
    eLocContextError,
    eLocMemoryError
} tLocGetStatus; 

typedef void *tLocFindCtx;

typedef void *tLocation;    

PREFIX unsigned int POSTFIX LocGetLocations
(
    tLocFindCtx pCtx, 
    tLocation *pLoc,
    unsigned int pNumLocations,
    tLocGetStatus *pStatus
);

In C#, I have this:

[DllImport(@"VertexNative\Location.dll")]
public static extern uint LocGetLocations(IntPtr findContext, out byte[] locations, uint numberLocations, out int status);

The problem is that I don't quite know how to handle the pLoc parameter in C#. I'm bringing it over as a byte array, although I'm not sure if that is correct. The C library's documentation says that that parameter is a pointer to an array of handles.

How can I get an array back on the C# side and access its data?

The example I was given in C, looks like this:

tLocation lLocation[20];

// other stuff

LocGetLocations(lCtx, lLocation, 20, &lStatus)

Any help would be much appreciated!


回答1:


Generally, the only thing that matters is the size of the parameters. As I recall enums are integers in C, so you can simply use that. Or better, recreate the same enum in C#, I think it would work. One thing to remember is that when dealing with complex structs, one needs to use attributes to tell the framework about the desired alignment of members.




回答2:


In the end, this signature works:

[DllImport(@"VertexNative\Location.dll")]
public static extern uint LocGetLocations(IntPtr findContext, [Out] IntPtr[] locations, uint numberLocations, out int status);

And I can call it like this (some refactoring needed):

IntPtr[] locations = new IntPtr[20];
int status;
// findContext is gotten from another method invocation
uint result = GeoCodesNative.LocGetLocations(findContext, locations, 20, out status);

Thanks for the help!



来源:https://stackoverflow.com/questions/4389950/how-to-map-a-c-array-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!