本文介绍了调用C ++导出函数在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C ++代码:

I have the following C++ code:

#pragma once
#include "StdAfx.h"
#include <string>
using namespace std;
using namespace System;


extern "C" __declspec( dllexport ) string __stdcall GetVale()
{
    return "test";
}

我试图在C#中调用这个函数:

I am trying to call this function in C# by doing this:

    [DllImport("Security.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "_GetVale@4")]
    internal static extern string Getvalue();

我这样做只是为了学习和理解真的。当我调用这个我得到一个PInvoke异常说我CallingConvention是不正确的。我相信我的错误在我的文件是非常小的。我知道切入点是_GetVale @ 4,因为我使用一个程序来找到它。如果我不能改变它到任何东西它抛出一个入口点没有找到,所以我的问题是其他地方。

I am doing this just to learn and understand really. When I call this I get a PInvoke exception saying my CallingConvention is not correct. I am sure my mistakes in my files are very small. I know the entry point is "_GetVale@4" for I used a program to find it. If I can't change that to anything else it throws a entry point not found, so my problem is some where else.

我做错了什么?谢谢!

推荐答案

不能对使用C ++类型的函数使用简单的p调用。您应该限制自己使用纯c。

You can't use simple p-invoke for functions that use C++ types. You should restrict yourself to pure c.

返回 char * 很少是正确的解决方案。

Returning a char* is rarely the correct solution. You get lifetime issues: It's unclear when and how the return value should be freed.

一个标准模式是调用者传递一个 char *

One standard pattern is the caller passing in a char* and a length, and the callee filling this buffer.

C

extern "C" __declspec( dllexport ) void __stdcall GetValue(char* buf, in length)

C#

[DllImport("Security.dll", CallingConvention = CallingConvention.StdCall, Charset = CharSet.Ansi]
internal static extern void GetValue(StringBuilder buf, int length);






有几种直接使用C ++的方法:


There are a few ways to work with C++ directly:


  1. 创建SWIG包装器

  2. 使用CXXI

这是一个有点恼人的工作,它需要一个C +边的包装器CXXI听起来很有趣,但我没有自己使用。

I'm not too fond of SWIG. It's a bit annoying to work with, and it requires a C++ sided wrapper. CXXI sounds interesting, but I haven't used it myself.

这篇关于调用C ++导出函数在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:57