Call C++ Exported Function in C# [closed]

断了今生、忘了曾经 提交于 2019-12-25 09:08:42

问题


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";
}

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();

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.

What exactly am I doing wrong? Thanks!


回答1:


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


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

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);

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

  1. Create a SWIG wrapper
  2. Use 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.



来源:https://stackoverflow.com/questions/9748156/call-c-exported-function-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!