问题
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:
- Create a SWIG wrapper
- 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