软件编程
位置:首页>> 软件编程>> C#编程>> c#调用c++的DLL的实现方法

c#调用c++的DLL的实现方法

作者:故里2130  发布时间:2023-10-27 05:27:40 

标签:c#,调用,c++,DLL

C#是托管型代码,创建的对象会自动回收。C++是非托管型代码,创建的对象需要手动回收(有时不手动回收,可能出现内存溢出的问题)。

C#调用C++的方式分为两种:(1)采用托管的方式进行调用;(2)非托管的方式进行调用。

1.采用托管的方式进行调用,就和正常调用c#的dll一样

创建新的c++项目

c#调用c++的DLL的实现方法

 Function.h中的代码,一个返回两数之和的方法,一个返回字符串的方法

#pragma once
#include <string>
public ref class Function
{
public:
   Function(void);
   ~Function(void);
   int menber;
   int menberFuncAdd(int a,int b);
   System::String^ say(System::String^ str);
};

//.cpp
#include "Function.h"
Function::Function(void)
{
}
Function::~Function(void)
{
}

int Function::menberFuncAdd(int a,int b)
{
  return a+b;
}
System::String^ Function::say(System::String^ str)
{
  return str;
}

Function.h中空白不用写

#include "Function.h"

注意:c++的项目一定要选择公共语言运行时支持

c#调用c++的DLL的实现方法

在c#的项目中像引用c#的dll一样引用

c#调用c++的DLL的实现方法

 代码中调用

c#调用c++的DLL的实现方法

Function fun = new Function();
           int a = fun.menberFuncAdd(1, 2);
           string s = fun.say("Hello World");

注意:c#项目一定要选择x86,否则要报错。

c#调用c++的DLL的实现方法

运行效果:

c#调用c++的DLL的实现方法

2.非托管的方式进行调用

创建新的c++项目

c#调用c++的DLL的实现方法

stdafx.h中的代码

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include "targetver.h"
#ifdef A_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
#define WIN32_LEAN_AND_MEAN             //  从 Windows 头文件中排除极少使用的信息
// Windows 头文件:
#include <windows.h>

extern "C" DLL_API void MessageBoxShow();

// TODO: 在此处引用程序需要的其他头文件

 dllmain.cpp中的代码

#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
                      DWORD  ul_reason_for_call,
                      LPVOID lpReserved
                    )
{
   switch (ul_reason_for_call)
   {
   case DLL_PROCESS_ATTACH:
   case DLL_THREAD_ATTACH:
   case DLL_THREAD_DETACH:
   case DLL_PROCESS_DETACH:
       break;
   }
   return TRUE;
}

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

void MessageBoxShow()
{
   MessageBox(NULL, TEXT("Hello World"), TEXT("In a DLL"), MB_OK);
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

注意:c++的项目一定要选择公共语言运行时支持

c#调用c++的DLL的实现方法

在代码加上

[DllImport("ll.dll")]
public extern static void MessageBoxShow();

c#调用c++的DLL的实现方法

 注意:c#项目一定要选择x86,否则要报错。

c#调用c++的DLL的实现方法

运行结果:

c#调用c++的DLL的实现方法

来源:https://blog.csdn.net/u012563853/article/details/123696733

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com