hweesung
hweesung

Reputation: 1

How to use a class defined in c# dll from c++ code

I have a dll that was written in c#, and I used this dll in my c++ code(exactly MFC). I can use dll function with return value int, string... But I need to use a function with return value c# class! I don't know what kind of data type in MFC for putting in the function's return value in c# dll. c# return value object is convert to _variant_t in MFC. Please help me. Thank you for reading my question

C# code (abstract)

[Guid(" - - - - ")]
public interface ITestClass
{
     object Func();
}

[Guid(" - - - - ")]
public class TestClass : ITestClass
{
   public object Func()
   {
       Project1.Class1 data = dataList[0];
       return data ;
   }
}

MFC code (abstract)

ITestClass *ptc = NULL;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(CLSID_TestClass, NULL, CLSCTX_INPROC_SERVER, IID_ITestClass, reinterpret_cast<void**>(&ptc));

int sum = ptc->Sum(5, 30); // It is perfect

data = ptc->Func(); // I don't know what data type is

Upvotes: 0

Views: 216

Answers (1)

Adam Jachocki
Adam Jachocki

Reputation: 2125

you will have to have same class defined in C++. It's kind of hard and may be buggy. So I would try with CLI.

Or there is a simpler way. Don't do that :) Exept, use old, good mechanism, like:

int objectHandle = ptc->CreateObject();
int data = ptc->GetSomeIntData(objectHandle);
ptc->DoSomeOperation(objectHandle);
ptc->ReleaseObject(objectHandle);

The idea is that you don't have a class on C++ side. The object is created on C# side and has its unique object handle (it may be hashcode). You return this handle in CreateObject and on C# side you can store your object in a dictionary:

Dictionary<int, MyClass>

Then on C++ side you call functions with your objectHandle.

It's far more easier way to acomplish the same result.

But if you really want to use this class, you can try this: - make sure that you C# lib is com compatible (Register for COM interop option) - After compiling C# lib, there should be a tlb file. Import it in c++:

#import "path\to\lib.tlb"

next you can use it like this:

CoInitialize(NULL);
ClassNamespace::ITestClassPtr myClass(__uuidof(ClassNamespace::TestClass));
myClass->Func();
CoUninitialize();

You can also wrap all that functionality in C++ class. That of course creates more work and makes you have to keep two similar codes (real class and wrapper class). But may be more friendly to use.

If you want to return other class, you would have to do it in similar way. Create com interface, use it in c++ and return it in c#.

Upvotes: 1

Related Questions