DLL-P/Invoke to C++ class

  • Thread starter Jeffrey B. Holtz
  • Start date
J

Jeffrey B. Holtz

I've read the posts about instantiating a class from a dll in C# and
then even accessing the class method via the
CallingConvention=CallingConvention.ThisCall. Now I have a Class
defined in the header dll which has a pure virtual method. Inside the
dll a specific class is created which then implements the pure
virtual. The base class, defined in the header is being returned to
the C# program. I cannot get the EntryPoint (via Depends) to any pure
virtual function. And if I give the base class a default
implementation, the call from the C# app will call the base
implementation and not the derived implementation. Any ideas?

i.e. The following will return 1 instead of 2. And I don't know how
to get 3

DllHeader.h
-----------
class BaseClass
{
virtual int PureVirtual_Method() = 0;
virtual int Virtual_Method();
}
extern "C" STP_API BaseClass * CreateSubClass();

DllHeader.cpp
-------------
int BaseClass::Virtual_Method() { return 1; }
extern "C" STP_API BaseClass * CreateSubClass()
{
return new SubClass();
}

InternalHeader.h
----------------
class SubClass
{
virtual int PureVirtual_Method();
virtual int Virtual_Method();
}

InternalHeader.cpp
------------------
int SubClass::pureVirtual_Method() { return 3; }
int SubClass::Virtual_Method() { return 2; }

Class.cs
--------
public class BaseClass : IDisposable
{
private IntPtr _this = IntPtr.Zero;

public BaseClass()
{
_this = CreateSubClass();
}

public int Virtual_Method()
{
return CppClass_Virtual_Method(_this);
}

[DllImport(@"CppClass.dll")]
private static extern IntPtr CreateSubClass();

[DllImport(@"CppClass.dll", EntryPoint="#1",
CharSet=CharSet.Unicode,
CallingConvention=CallingConvention.ThisCall)]
private static extern int CppClass_Virtual_Method(IntPtr
instance);
}
 
M

Mattias Sjögren

Jeffrey,

If you can modify the C++ code, I'd add a function like this

extern "C" STP_API int CallMethod(BaseClass *p)
{
return p->PureVirtual_Method();
}



Mattias
 
J

Jeffrey Holtz

Well great minds think alike. I started doing that soon after I posted
the message. That seems like the only way to get either the virtual or
pure virtual to call the SubClass. This means though that if you don't
have the source code (luckily I do, although I'm trying to maintain a
common interface for C++ lib interface and C# P/Invoke interface) you
will have to write a wrapper class or dll to interface. Thanks for the
response though.

Jeff

*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top