C#中调用C++代码

来源:互联网 发布:淘宝代销是什么意思 编辑:程序博客网 时间:2024/06/11 07:52
C# 中调用C++代码
int 类型
[DllImport(“MyDLL.dll")]
//返回个int 类型
public static extern int mySum(int a1,int b1);
//DLL中申明
extern “C”__declspec(dllexport) int WINAPI mySum(int a2,int b2)
{
//a2 b2不能改变a1 b1
//a2=..
//b2=...
return a+b;
}
//参数传递int 类型
public static extern int mySum(ref int a1,ref int b1);
//DLL中申明
extern “C”__declspec(dllexport) int WINAPI mySum(int *a2,int*b2)
{
//可以改变 a1, b1
*a2=...
*b2=...
return a+b;
}

DLL 需传入char *类型
[DllImport(“MyDLL.dll")]
//传入值
public static extern int mySum(string astr1,string bstr1);
//DLL中申明
extern “C”__declspec(dllexport) int WINAPI mySum(char * astr2,char *bstr2)
{
//改变astr2 bstr 2 ,astr1bstr1不会被改变
return a+b;
}

DLL 需传出char *类型
[DllImport(“MyDLL.dll")]
// 传出值
public static extern int mySum(StringBuilder abuf, StringBuilder bbuf );
//DLL中申明
extern “C”__declspec(dllexport) int WINAPI mySum(char * astr,char *bstr)
{
//传出char * 改变astr bstr-->abuf, bbuf可以被改变
return a+b;
}
DLL 回调函数
BOOL EnumWindows(WNDENUMPROClpEnumFunc, LPARAM lParam)
using System;
usingSystem.Runtime.InteropServices;
public delegate boolCallBack(int hwnd, int lParam); //定义委托函数类型
public classEnumReportApp
{
[DllImport("user32")]
public static extern intEnumWindows(CallBack x, int y);
public static void Main(){
CallBack myCallBack = newCallBack(EnumReportApp.Report); EnumWindows(myCallBack,0);
}
public static bool Report(inthwnd, int lParam)
{
Console.Write("Window handle is");
Console.WriteLine(hwnd); returntrue;
}
}
DLL 传递结构
BOOL PtInRect(const RECT *lprc,POINT pt);
usingSystem.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point{
public int x;
public int y;
}
[StructLayout(LayoutKind.Explicit)]
public struct Rect
{
[FieldOffset(0)] public intleft;
[FieldOffset(4)] public inttop;
[FieldOffset(8)] public intright;
[FieldOffset(12)] public intbottom;
}
Class XXXX {
[DllImport("User32.dll")]
public static extern boolPtInRect(ref Rect r, Point p);
}
0 0
原创粉丝点击