Search code examples
c#c++unmanageddllexport

How to export C# dll method/functions to use it in C++


I have done my part of coding in C#, a small method is given as below

 public  static unitdefn GetUnit(XmlDocument doc)
    {

        XmlNodeList nodeList1 = (XmlNodeList)doc.DocumentElement.SelectNodes("//UnitDefinitions/Unit");
        int countdefn = nodeList1.Count;
        unitdefn[] arrunt = new unitdefn[countdefn];
        if (countdefn != 0)
        {

            int i = 0;
            foreach (XmlNode node in nodeList1)
            {
                XmlAttribute att = node.Attributes["name"];
                if (att != null)
                {
                    string idu = node.Attributes["name"].Value;
                    //System.Console.WriteLine(id1);
                    arrunt[i].name = idu;
                }
                i++;
            }

        }
        return arrunt[0];
    }

and i want this method to be used in my C++ project and i have done as given below

int  xmlRead()
{

int x=1,s=1;
char xmldllpath[1000]="//dllpath";
HMODULE h = LoadLibrary(xmldllpath);

if (!h) {
    printf("error: Could not load %s\n", xmldllpath);
    return 0; // failure
}

getAdr(&s, h, "GetUnit");
}

the dll is loaded successfully but it is not fetching that method any specific way to do it


Solution

  • Don't. Exporting methods from C# is not supported. It is just barely possible by manually editting the emitted assembly, but really - don't.

    There's a few proper solutions you could use:

    • Use a C++/CLI project to expose the managed methods to unmanaged code
    • Use COM (.NET is basically COM 2.0, so this is very easy; it's also quite easy to consume on the C++ side)
    • Pass a delegate to the unmanaged code on initialization, and call that when needed
    • Use some other method of inter-process communication (e.g. named pipes, TCP...)