C# DllImport library written on C++

前端 未结 3 985
一个人的身影
一个人的身影 2021-01-16 19:25

I\'m pretty new in C#. I have Dll written on C++ by myself and I\'m going to use functions from that dll in C# app.

So, I do the following when declare functions in

3条回答
  •  庸人自扰
    2021-01-16 20:17

    You are defining a C++ function without an extern "C" block. As C++ allows you to overload functions (i.e. create many captureCamera() functions with different sets of arguments), the actual function name inside the DLL will be different. You can check it by opening Visual Studio Command prompt, going to your binary directory and running this:

    dumpbin /exports YourDll.dll
    

    You will get something like this:

    Dump of file debug\dll1.dll
    
    File Type: DLL
    
      Section contains the following exports for dll1.dll
    
        00000000 characteristics
        4FE8581B time date stamp Mon Jun 25 14:22:51 2012
            0.00 version
               1 ordinal base
               1 number of functions
               1 number of names
    
        ordinal hint RVA      name
    
              1    0 00011087 ?captureCamera@@YAHAAH@Z = @ILT+130(?captureCamera@@YAHAAH@Z)
    
      Summary
    
            1000 .data
            1000 .idata
            2000 .rdata
            1000 .reloc
            1000 .rsrc
            4000 .text
           10000 .textbss
    

    The ?captureCamera@@YAHAAH@Z is the mangled name that actually encodes the arguments you've specified.

    As mentioned in other answers, simply add extern "C" to your declaration:

    extern "C" __declspec(dllexport) int captureCamera(int& captureId)
    {
        ...
    }
    

    You can recheck that the name is correct by rerunning dumpbin:

    Dump of file debug\dll1.dll
    
    File Type: DLL
    
      Section contains the following exports for dll1.dll
    
        00000000 characteristics
        4FE858FC time date stamp Mon Jun 25 14:26:36 2012
            0.00 version
               1 ordinal base
               1 number of functions
               1 number of names
    
        ordinal hint RVA      name
    
              1    0 000110B4 captureCamera = @ILT+175(_captureCamera)
    
      Summary
    
            1000 .data
            1000 .idata
            2000 .rdata
            1000 .reloc
            1000 .rsrc
            4000 .text
           10000 .textbss
    

提交回复
热议问题