C#引用C++ Dll问题
- C/C++ code
typedef struct _COMMPORTCONFIG {DWORD BaudRate; // baud rateDWORD ByteSize; // number of bits/byte, 4-8DWORD Parity; // 0-4=no,odd,even,mark,spaceDWORD StopBits; // 0,1,2 = 1, 1.5, 2DWORD fOutxCtsFlow; // CTS Flow Control} COMMPORTCONFIG;C/C++:BOOL MetrocomInitCommunication(int i_port, COMMPORTCONFIG * p_config);
现在我如何转成C#可以引用的,还有要怎么调用?
[解决办法]
DWORD可以使用Int类型,在C#里声明Struct来对应_COMMPORTCONFIG ,然后像调用API一样来调用这个C++的函数,使用Ref传递结构。
[解决办法]
类似的,看看吧
- C# code
DLL 传递结构 (见代码)BOOL PtInRect(const RECT *lprc, POINT pt); using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct Point {public int x; public int y;} [StructLayout(LayoutKind.Explicit)] public struct Rect { [FieldOffset(0)] public int left; [FieldOffset(4)] public int top;[FieldOffset(8)] public int right; [FieldOffset(12)] public int bottom;} Class XXXX { [DllImport("User32.dll")] public static extern bool PtInRect(ref Rect r, Point p); }
[解决办法]
public struct COMMPORTCONFIG
{
int BaudRate; // baud rate
int ByteSize; // number of bits/byte, 4-8
int Parity; // 0-4=no,odd,even,mark,space
int StopBits; // 0,1,2 = 1, 1.5, 2
int fOutxCtsFlow; // CTS Flow Control
}
[DllImport("DLL文件名")]
public static extern bool MetrocomInitCommunication(int i_port, ref COMMPORTCONFIG p_config);
[解决办法]
- C# code
[DllImport("你DLL名称")] public static extern bool MetrocomInitCommunication(int i_port, ref COMMPORTCONFIG p_config);[StructLayout(LayoutKind.Sequential)] public struct _COMMPORTCONFIG {int BaudRate; // baud rateint ByteSize; // number of bits/byte, 4-8int Parity; // 0-4=no,odd,even,mark,spaceint StopBits; // 0,1,2 = 1, 1.5, 2int fOutxCtsFlow; // CTS Flow Control}int i_port;COMMPORTCONFIG p_config=new COMMPORTCONFIG ();MetrocomInitCommunication(i_port, ref p_config);
[解决办法]