问题描述
我有 .lib 文件及其标头 (.h) 文件.该文件有一些需要在 C# 应用程序中使用的函数.
I have .lib file with its header (.h) file. This file have a few functions that need to be used in C# application.
谷歌搜索后,我发现我需要从这个静态库创建一个动态 DLL,并使用互操作从 C# 代码中调用这个动态 DLL.
After googling I found that I need to create a dynamic DLL from this static library and call this dynamic DLL from C# code using interop.
我已经创建了一个 win32 项目并选择了类型 DLL.
I have created a win32 project and selected type DLL.
包含头文件并将 .lib 添加到其他依赖项中.
Included header file and added .lib to additional dependencies.
我能够看到静态库中定义的函数(当我按下 ctrl + space 时).
I am able to see the functions defined in the static library (when I press ctrl + space).
作为一个新手,我不知道如何导出函数,即在具有以下签名的 .lib 中:
As a total newbie I do not know how I can export the function, which is, in .lib with following signature:
void testfun( char* inp_buff, unsigned short* inp_len, char* buffer_decomp,unsigned *output_len,unsigned short *errorCode)
我想在动态 DLL 中使用不同名称的相同签名.
I want same signature in my dynamic DLL with a different name.
头文件和.cpp文件要写什么?
What to write in header file and .cpp file?
推荐答案
如果你可以重新编译你的 lib,只需将 __declspec(dllexport)
添加到你想要导出的所有函数的签名中.
If you can recompile your lib, just add __declspec(dllexport)
to the signatures of all of the functions you want to be exported.
void __declspec(dllexport) testfun( char* inp_buff, unsigned short* inp_len, char* buffer_decomp,unsigned *output_len,unsigned short *errorCode)
如果你不能这样做,那么你可以通过编写一个 .def 文件来导出它们.使用 def 文件,您甚至可以在导出函数时更改其名称.http://msdn.microsoft.com/en-us/library/28d6s79h.aspx
If you can't do that, then you can export them by writing a .def file instead. Using def files you can even change the name of a function as it is exported.http://msdn.microsoft.com/en-us/library/28d6s79h.aspx
---- mylib.def 的内容----
---- contents of mylib.def ----
LIBRARY
EXPORTS
testfun
newname=testfun2
然后当你链接dll时,包含mylib.def
Then when you link the dll, include mylib.def
link /dll /machine:x86 /def:mylib.def mylib.lib
编辑 2:
请注意 pinvoke 假定您导入的函数将具有 _stdcall 调用约定,除非您另有说明.因此,您可能也需要在 C# 代码中执行此操作.
note that pinvoke assumes that the functions you import will have _stdcall calling convention unless you say otherwise. So you might need to do this as well, in your C# code.
[DllImport("mylib.dll", CallingConvention=CallingConvention.Cdecl)]
或者,您可以将 C++ 代码更改为 __stdcall
Or, you could change your C++ code to be __stdcall
void __declspec(dllexport) __stdcall testfun( char* inp_buff, ...
这篇关于将静态链接库转换为动态 dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!