C++
Call c++ dll functions from c#
// CplusConsoleApp.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;
extern "C" __declspec(dllexport) void fun1(){
cout << "This is output from a c++ program function called fun1 \n";
}
C:\app\DLLs>dumpbin /exports c:\app\DLLs\CplusConsoleApp.dll
Microsoft (R) COFF/PE Dumper Version 12.00.21005.1
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file c:\app\DLLs\CplusConsoleApp.dll
File Type: DLL
Section contains the following exports for CplusConsoleApp.dll
00000000 characteristics
58D17336 time date stamp Tue Mar 21 14:38:46 2017
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 000012C0 fun1 = _fun1
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
2000 .text
C:\app\DLLs>TestMisc.exe
This is output from a c++ program function called fun1
using System;
using System.Runtime.InteropServices;
namespace TestMisc {
static class Program {
[DllImport("CplusConsoleApp.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void fun1();
static void Main(string[] args) {
fun1();
}
}
- Create c++ proj ---- ensure your entrypoint class uses namespace std
- Add a function declared extern "C" __declspec(dllexport)
- compile, and verify the exported function via dumpbin /exports
- Create c# project ---- ensure your class using System.Runtime.InteropServices;
- Reference the c++ dll function like [DllImport("CplusConsoleApp.dll"
- specify callingConvention as C (so c# can find the functions normal/friendly name)
- Call the function (like ANY other normal c# managed function)
// CplusConsoleApp.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;
extern "C" __declspec(dllexport) void fun1(){
cout << "This is output from a c++ program function called fun1 \n";
}
C:\app\DLLs>dumpbin /exports c:\app\DLLs\CplusConsoleApp.dll
Microsoft (R) COFF/PE Dumper Version 12.00.21005.1
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file c:\app\DLLs\CplusConsoleApp.dll
File Type: DLL
Section contains the following exports for CplusConsoleApp.dll
00000000 characteristics
58D17336 time date stamp Tue Mar 21 14:38:46 2017
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 000012C0 fun1 = _fun1
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
2000 .text
C:\app\DLLs>TestMisc.exe
This is output from a c++ program function called fun1
using System;
using System.Runtime.InteropServices;
namespace TestMisc {
static class Program {
[DllImport("CplusConsoleApp.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void fun1();
static void Main(string[] args) {
fun1();
}
}
Comments
Post a Comment