Import unmanaged C++ class from dll issue

M

madbat87

Hi,
I'm trying to import code from a c++ unmanaged dll in a c# project.

In the dll there's a class named Connection, but the dll exposes only
2 methods (outside the class):
- HBITMAP DownloadIntra(char *host, int port, char *user, char *pwd,
int channel);
- Connection* CreateConnection(char *host, int port, char *user, char
*pwd);

My friend was able to import them in a C++ .Net project with:

- extern "C" __declspec(dllimport) HBITMAP __cdecl DownloadIntra(char
*host, int port, char *user, char *pwd, int channel);

- extern "C" __declspec(dllimport) Connection* __cdecl
CreateConnection(char *host, int port, char *user, char *pwd);

He created the Connection class wrapper with virtual methods:
class Connection
{
public:
virtual int __stdcall disconnect() = 0;
virtual int __stdcall authenticate() = 0;
virtual int __stdcall getPort() = 0;
virtual int __stdcall connected() = 0;
virtual int __stdcall getChannelsCount() = 0;
virtual char* __stdcall getThreadID() = 0;
virtual void __stdcall FreeConnection() = 0;
virtual void __stdcall usePing(bool ping) = 0;
virtual bool __stdcall isPingActive() = 0;
};

In my C# project I was able to import and correctly use the first
method with:

[DllImport("vslib.dll")]
public static extern IntPtr DownloadIntra(string host, int port,
string user, string pwd, int canale);

For the second method:
I created my wrapper for the Connection class:

public abstract class Connection
{
public abstract int Disconnect();
public abstract int Authenticate();
public abstract int GetPort();
public abstract int Connected();
public abstract int ChannelCount();
public abstract string GetThreadID();
public abstract void FreeConnection();
public abstract void UsePing(bool use);
public abstract bool IsPingActive();
}

And Imported the method:
[DllImport("vslib.dll")]
public static extern Connection CreateConnection(string host, int
port, string user, string pwd);

The problem is:
In my project I create a Connection object with the CreateConnection
method:
Connection conn = CreateConnection("10.0.0.10", 80, "user", "pwd");
But after this, I noticed that the code executes the first method
(disconnect) instead of only create the Connection object, and then
the .net raises an exception
 
N

Nicholas Paldino [.NET/C# MVP]

The way that you are exposing the class is incorrect. You should be
using C++/CLI to create the managed wrapper in C++ and exposed as a .NET
assembly. The thing is, you wouldn't be able to export the function from
that assembly as well (AFAIK). You would have to expose it as a static
method on a class in that assembly.
 

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