日期:2014-05-18  浏览次数:20746 次

c#中如何访问调用 c++写的dll,有库文件.
最近用VS C#2005 编写一个通信界面,需要调用C++编写的.dll文件,该文件在VS c++ 2005 中可以成功调用。
调用的相关代码:
头文件:1582.h
int __stdcall ReadData1582(int pipenum,unsigned char *recbuffer,int len,int waittime=-1);
int __stdcall WriteData1582(int pipenum,unsigned char *sendbuffer,int len,int waittime=-1);

调用的函数是:ReadData1582和WriteData1582

我搜索了一些帖子,做了些尝试但是都失败了。
1 regsvr32注册DLL 报错:Dllname was loaded, but the DllRegisterServer or DllUnregisterServer entry point was not found。但是我的文件名字并没有写错。
2 项目 添加引用 浏览 报错:请确定此文件可访问并且是一个有效的程序集或COM组件;

希望各位能够提供帮助,告知相关的步骤。如果可以请提供相关的C#代码,谢谢了!(本人分数不多,请包涵!)

------解决方案--------------------
可以使用
[DllImport("dll名称")]
private static extern int 方法名称(参数类型1 参数1,参数类型2 参数2);来重新在你的C#中声明方法,
------解决方案--------------------
C#不能直接链接到C++库文件(.lib),如果C++没有导出ReadData...函数,你需要建一个dll导出那两个函数。
C#可以用P/Invoke来使用dll的导出函数,参考1楼和2楼的帖子。
------解决方案--------------------
extern "C" __declspec(dllexport) int __stdcall ReadData1582(int pipenum,unsigned char *recbuffer,int len,int waittime=-1); 
是用在C++代码中的 dll导出函数