C# marshaling C struct -


i've c-c# code works:

.h

typedef struct {    float a;   float b;  } mystruct;  extern mystruct mystruct;  __declspec(dllexport) void  getmystruct (mystruct* s); __declspec(dllexport) void  setmystruct (mystruct* s); 

.c

    mystruct mystruct;      void getmystruct (mystruct* s)     {          *s = aerolink_iopkt;     }      void setmystruct (mystruct* s)     {          aerolink_iopkt = *s;      }  void test() {    // code update element in struct    // mystruct.a = 0.4;    // mystruct.a = 0.1; } 

.cs

public struct mystruct {    public float a;   public float b;  }    [dllimport(dll_name, entrypoint = "getmystruct")] protected static extern void getmystruct(ref mystruct s);  [dllimport(dll_name, entrypoint = "setmystruct")] protected static extern void setmystruct(ref mystruct s); 

this way, every time need set data c# c, must call void setmystruct , vice-versa if want data c (updated void test) c# must call getmystruct. must 50 times per seconds.

is there way avoid calling setmystruct , getmystruct every time? use setmystruct 1 time , have changes reflected, , to. not know if possible.

you can unsafe , pointers.

you need compile c# program "unsafe" enabled.

edit: better way:

add following function library:

__declspec(dllexport) void  getmystructref (mystruct** s); void getmystructref(mystruct** s) {     *s = &mystruct; } 

in c#:

[dllimport(dll_name, entrypoint = "getmystructref")] protected static extern void getmystructref(ref mystruct* s);  mystruct* data; getmystructref(ref data); console.writeline($"{data->a} {data->b}"); 

old answer:

unsafe class myclass : idisposable {     [dllimport(dll_name, entrypoint = "getmystruct")]     protected static extern void getmystruct(mystruct* s);      [dllimport(dll_name, entrypoint = "setmystruct")]     protected static extern void setmystruct(mystruct* s);      gchandle handle;     mystruct* structref;      public void myclass()     {         //we need pinned reference struct         handle = gchandle.alloc(new mystruct(), gchandletype.pinned);         structref = (mystruct*)handle.addrofpinnedobject().topointer();          setmystruct(structref);     }      public void dispose()     {         //we need free handle release memory         //gc not collect without         handle.free();     } } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -