delphi - Accessing managed object in a c# callback passed to a native dll -


i'm trying pass c# callback function native dll. works fine, couldn't find way access parent object of callback method. here's code demonstrates want do:

class myform: form {   public delegate void callbackdelegate(intptr thisptr);    [dllimport("mylib.dll", callingconvention = callingconvention.stdcall)]   public static extern void test(callbackdelegate callback);    int field;    static void callback(intptr thisptr)   {       // need reference class field field here.       myform thisobject = ?magicmethod?(thisptr);        thisobject.field = 10;   }    void callexternalmethod()   {       test(callback);   } } 

i tried getting pointer of this got following exception: "object contains non-primitive or non-blittable data.". should mention parent object windowsforms form.

update

the dll written in delphi , signature of test function following:

type   tcallback = procedure of object; stdcall;  procedure test(callback: tcallback); stdcall; 

i received above error message when tried pointer class following code:

var ptr = gchandle.alloc(this, gchandletype.pinned).addrofpinnedobject(); 

you on thinking this. c# marshalling create thunk around delegate. must not attempt so.

on delphi side write this:

type   tcallback = procedure; stdcall; 

simply remove of object.

on c# side delegate is:

public delegate void callbackdelegate(); 

the method use delegate looks this:

void callback() {     // instance method, *this* available } 

and call native code this:

void callexternalmethod() {     test(callback); } 

so, let's put together. on delphi side can write:

library mylib;  type   tcallback = procedure; stdcall;  procedure test(callback: tcallback); stdcall; begin   callback; end;  exports   test;  begin end. 

and on c# side:

class myform: form {     public delegate void callbackdelegate();      [dllimport("mylib.dll")]     public static extern void test(callbackdelegate callback);      int field;      static void callback()     {         field = 10;     }      void callexternalmethod()     {         field = 0;         test(callback);         debug.assert(field == 10);     } } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -