How to Expose C Static Library to .Net?

前端 未结 1 690
别跟我提以往
别跟我提以往 2021-01-27 17:30

What are the steps to expose C++ functions to C and .Net? I want to use the same function names in C++, C and .Net for 32-bit and 64-bit builds.

I\'m posting this questi

相关标签:
1条回答
  • 2021-01-27 17:35

    The steps are:

    1. Expose C++ functions as a C static library (.lib).

    2. Use #pragma statements to project the lib's functions into a DLL.

    3. Use .Net's DllImport attribute to expose the DLL's functions.

    For an example, see this github project.

    Step 1. Create a static library project. Create a C++ file that exposes each function as a C function.

    extern "C" {
      void vfunc(void) { return; }
      int ifunc(int i) { return i; }
    }
    

    Step 2. Create a DLL project. Specify the static library as an "Additional Dependency". Create a C file and put #pragma statements to project each static lib function into the .DLL. You'll need to define two #pragmas, one for 32-bit and another for 64-bit. The difference being that 32-bit requires a leading underscore before the function name. No code necessary, just #pragmas.

    #ifdef _M_X64
    #define Alias(func) comment(linker, "/export:" func "=" func)
    #else
    #define Alias(func) comment(linker, "/export:" func "=_" func)
    #endif
    
    #pragma Alias("vfunc")
    #pragma Alias("ifunc")
    

    Step 3. Create a .Net project. Use DllImport attribute to expose each function.

    class Program
    {
        [DllImport("c-dll.dll")]
        extern static void vfunc();
        [DllImport("c-dll.dll")]
        extern static void ifunc();
        static void Main(string[] args)
        {
            vfunc();
            int i = ifunc(1);
        }
    }
    

    While coding is straightforward using these techniques, you'll need to do quite a bit of editing of solution and project files.

    1. Set the solution's correct build order. The DLL will depend on the static library. The .Net projects will depend on the DLL.

    2. Manually edit the DLL project file to build the 32-bit and 64-bit DLLs into separate directories (e.g. Win32\Debug, x64\Debug).

    3. Manually edit the .Net project files to create sections for combinations of x86/x64 and Debug/Release (4 total). DO NOT USE AnyCPU. DllImport WILL NOT WORK WITH AnyCPU. USE ONLY x86/x64.

    4. Manually edit the .Net project file output path to be the same Win32/x64 directories as above. This will allow DllImport to find the DLL since DLL/EXE share the same directory. Optionally you can put the DLL into a discoverable directory or put a path in DllImport -- but that's problematic when you are using two DLLs (32/64).

    0 讨论(0)
提交回复
热议问题