架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 11203|回复: 0

[WinForm] 如何在C#中调用C/C++ DLL中的方法

[复制链接]
发表于 2015-2-5 20:52:39 | 显示全部楼层 |阅读模式

一,创建C++ DLL项目


01154LO8-0.jpg
01154K0G-1.jpg

修改 CPPTest.cpp 内容为:

// CPPTest.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include

#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
extern "C"
{

struct TestStruct
{
int i;
char* str;
};

_declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{
return strlen(str);
}

_declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{
return a+b;
}

_declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{
using namespace std;
cout<<s.i<<endl;
cout<<s.str<<endl;
s.i=54321;
s.str="They are all dead!";
}
}

#ifdef _MANAGED
#pragma managed(pop)
#endif


二,创建C#测试项目

01154HV1-2.jpg
修改Program 内容为:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplicationTestCSharp
{
class Program
{
[DllImport("CPPTest.dll")]
static extern int GetStringLength(ref string str);

[DllImport("CPPTest.dll")]
static extern int AddTwoNumber(int a, int b);

[DllImport("CPPTest.dll")]
static extern void StructTest(ref TestStruct s);

static void Main(string[] args)
{
string testString = "HAHA! I am a test string";

Console.WriteLine("length(C++)=" + GetStringLength(ref testString).ToString());
Console.WriteLine("length(C#)=" + testString.Length.ToString());
Console.WriteLine("a+b(C++)=" + AddTwoNumber(10, 1000));
Console.WriteLine("a+b(C#)=" + (10 + 1000));

TestStruct s = new TestStruct();
s.i = 12345;
s.str = "Go to shoot evils on moutains!";
StructTest(ref s);
Console.WriteLine(s.i);
Console.WriteLine(s.str);
Console.ReadKey();
}

[StructLayout(LayoutKind.Sequential)]
public struct TestStruct
{
public int i;
public string str;
}
}
}

请留意以上介个DllImportAttribute标记的方法

运行结果:

length(C++)=24
length(C#)=24
a+b(C++)=1010
a+b(C#)=1010
12345
Go to shoot evils on moutains!
54321
They are all dead!

三,关于C/C++中几个关键字的说明

_declspec

__stdcall

extern


"C"
(dllexport) 使用 __declspec(dllexport) 从 DLL 导出
</s.str<<endl;
</s.i<<endl;




上一篇:用Winmail搭建邮件服务器
下一篇:C#动态态引用DLL的方法(转载)
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2024-5-13 10:07

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表