How to send a struct by ref containing a string from C# to unmanaged C++ library -


i need send struct c# managed code c library. c library populate values in struct. have been trying pass struct reference c# code updated data values.

this example c function in libshlib.so:

void sharedstruct(struct data* d) {    d->number = calcsomething();    d->message = dosomething(); } 

i can send individual parameters (int , stringbuilder) , library code runs , returns new values c# code called it.

but how can create struct in c# contains both int , string , send unmanaged code (c library) populate values used in c# code?

the c struct might this:

struct data {   int number;   char* message; }; 

right i'm trying establish best way manipulate data in c library use in c#. writing both pieces of code flexible right haven't been able working.

if want struct populated c code, looking out variable. note mono runtime default use free() deallocate strings pass in , might have take care padding in structures (see structlayout stuff in msdn). strings, further problems can had character sets.

sample code:

managed.cs:

using system; using system.runtime.interopservices;  struct data {     public int number;     public string message; }  class managed {     [dllimport("unmanaged")]     extern static void foo(out data data);     static void main()     {         data data;         foo(out data);         console.writeline("number = {0}, message = {1}", data.number, data.message);     } } 

unmanaged.c:

#include <string.h>  struct data {     int number;     char* message; };  void foo(struct data* data) {     data->number = 42;     data->message = strdup("hello unmanaged code!"); } 

test run:

$ mcs managed.cs $ gcc -shared -fpic -o libunmanaged.so unmanaged.c $ ld_library_path=$pwd mono managed.exe number = 42, message = hello unmanaged code! 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -