Skip to content

Instantly share code, notes, and snippets.

@Ch3shireDev
Created June 24, 2022 14:20
Show Gist options
  • Select an option

  • Save Ch3shireDev/e6606a98cd10bfcc3f237d6c4094c161 to your computer and use it in GitHub Desktop.

Select an option

Save Ch3shireDev/e6606a98cd10bfcc3f237d6c4094c161 to your computer and use it in GitHub Desktop.
Interoperability between C++ and C# - two ways

Example shows process run in C++ (Borland C++ 5.5) that calls dll compiled in C# (.NET compiler). Process loads library from C# DLL, then obtains pointer to own library and sends it to C#. C# using pointer to library in C++ loads it's exported function func() (with name _func). Then C# calls C++, when C++ calls C#.

C++ side:

#include <vcl.h>

extern "C" __declspec( dllexport ) void func(){
    ShowMessage("hello from borland C++");
}

__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{

    HWND lib = LoadLibrary("ClassLibrary1.dll");
    HWND addr = GetProcAddress(lib, "GetPointer");
    void(*getPointer)(HWND) = reinterpret_cast<void(*)(HWND)>(addr);
    HWND ownLib = GetModuleHandle(NULL);
    HWND addr3 = GetProcAddress(ownLib, "_func");
    getPointer(ownLib);
}

C# side:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ClassLibrary1
{
    public class Class1
    {
        [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

        [DllExport]
        public static int Fun()
        {
            MessageBox.Show("hello from C#");
            return 5;
        }

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate void Sub();

        [DllExport]
        public static void GetPointer(IntPtr appLib)
        {
            IntPtr funcPtr= GetProcAddress(appLib, "_func");
            Sub sub = (Sub)Marshal.GetDelegateForFunctionPointer(funcPtr, typeof(Sub));
            sub();
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment