David
David

Reputation: 2563

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?

Upvotes: 2

Views: 1368

Answers (2)

David Heffernan
David Heffernan

Reputation: 612954

You have to wrap the C++ objects up in free functions:

bool Connect(MyObject* obj)
{
    return obj->Connect();
}

and then export these from your DLL.

Alternatively you can make use of the fact that you are compiling with C++/CLI and export a managed C++/CLI class which can be consumed directly by your C# code.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754715

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();
  }
}

Upvotes: 7

Related Questions