main.h
#pragma once
#include<iostream>
#ifdef MAINDLL_EXPORTS
#define MAINDLL_API _declspec(dllexport)
#else
#define MAINDLL_API _declspec(dllimport)
// extern "C" 以C的方式导出,保证了接口名称不变
#endif
extern "C" {
int MAINDLL_API add(int a, int b);
int MAINDLL_API test(char* input);
}
main.cpp
#include "main.h"
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
// test
int add(int a, int b) {
return a + b;
}
int test(char* input) {
std::string content = input;
std::cout << content << std::endl;
// do somethings
return 0;
}
#include <iostream>
#include <Windows.h>
typedef int (*MainDll_Add)(int a,int b);
typedef int (*MainDll_Test)(char* input);
int main()
{
std::cout << "Hello World!\n";
HINSTANCE hInstLibrary = LoadLibrary(L"./MainDll.dll");
if (hInstLibrary) {
MainDll_Add func_add = (MainDll_Add)GetProcAddress(hInstLibrary, "add");
MainDll_Test func_test = (MainDll_Test)GetProcAddress(hInstLibrary, "test");
if (func_add) {
int res = func_add(1, 2);
std::cout << res << std::endl;
}
if (func_test) {
std::string text = "Hello";
char* textChar = const_cast<char*>(text.c_str());
int res = func_test(textChar);
if(res==0)
std::cout << "成功" << std::endl;
else
std::cout << "失败" << std::endl;
}
FreeLibrary(hInstLibrary); // 释放DLL
return 0;
}
}
// See https://aka.ms/new-console-template for more information
using System.Runtime.InteropServices;
namespace ConsoleApp3
{
class Program
{
[DllImport("MainDll.dll", EntryPoint = "add", CallingConvention = CallingConvention.Cdecl)]
extern static int add(int a, int b);
[DllImport("MainDll.dll", EntryPoint = "test", CallingConvention = CallingConvention.Cdecl)]
extern static int test(string input);
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine(add(1, 5));
string input = "Hello";
int res = test(input);
if(res == 0)
Console.WriteLine("成功");
else
Console.WriteLine("失败");
Console.ReadKey();
}
}
}