How to Expose C Static Library to .Net?

陌路散爱 提交于 2019-12-02 14:47:58

问题


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 question and answer because I haven't found these techniques documented anywhere.


回答1:


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).



来源:https://stackoverflow.com/questions/37358038/how-to-expose-c-static-library-to-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!