使用C#调用DLL中的C++函数

C++DLL与C#跨语言调用
本文介绍了一种使用P/Invoke从C#调用C++DLL的方法。通过示例展示了如何定义简单的C++函数并在C#中调用它。包括了必要的源代码及转换过程。
P/Invoke is an efficient method for calling native code functions in an unmanaged DLL. The below code samples show the source code a native code library which defines a very simple C++ function which accepts a char* argument.
MyLib.h
__declspec(dllexport) int Hello(char* pszBuffer, int nLengthObj);
MyLib.cpp
#include “stdafx.h”
#include “MyLib.h”
#include
__declspec(dllexport) int SayHello(char* pszBuffer, int nLengthObj)
{
::strcpy_s(pszBuffer, nLength, “Hello, from the C++ DLL”);
return strlen(pszBuffer);
}
LIBRARY “MyLib”
EXPORTS
Hello
From C#, calling this function is relatively simple. The below code shows this as well as when calling a method that takes char* you first need to convert the string to bytes.
[DllImport(“MyLib.dll”, ExactSpelling=false,
CallingConvention=CallingConvention.Cdecl, EntryPoint=”Hello”)]
public static extern int Hello(
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,int length);
static void Main(string[] args)
{
int size = 32;
//we need to manually marshal the bytes to a String
byte[] buffer = new byte[size];
int returnVal = Hello(buffer, size);
string result = Encoding.ASCII.GetString(buffer,0, returnVal);
Console.WriteLine(“”{0}”, return value: {1}”, result, returnVal);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值