Search code examples
c#.netc++-clipinvokeunmanaged

P/Invoke from C#: Call functions of returned object


I have a native/unmanaged DLL and it has a "CreateObject" function which returns a pointer to the business object.. so the call would be sth. like:

[DllImport("MyDll.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreateObject();

Question: The object is exposing public-functions like "Connect()" which i want to call, but i don't know how to "map" these calls so i have a simple method-signature like:

private bool Connect();

Any ideas?


Solution

  • The way to do this is to provide another PInvoke function which calls into a C function that does the method call

    [DllImport("MyDll.dll", CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.I1)]
    private static extern bool Connect(IntPtr businessObject);
    

    Then in C you define the following

    extern "C" {
      bool Connect(Business* pObject) {
        return pObject->Connect();
      }
    }