Strings in C ++?

My problem: I have some functions in a DLL, some of these functions, for example:

#include <string>
using namespace std;
extern "C" __declspec(dllexport) string __cdecl encryption(string s)
{
 return s;
}

Whenever I try to call this function from C #, here is the im code using:

[DllImport("Packer.dll", EntryPoint = "encryption")]
static extern string encryption(string s);

I get an error: PInvoke function call "Packer" has an unbalanced stack. This is likely due to the fact that the PInvoke managed signature does not match the unmanaged target signature. Verify that the calling agreement and PInvoke signature settings match the target unmanaged signature.

im guessing I get this error because I do not have the correct declarations for the function can anyone advise me how to fix this, thanks in advance

+1
source share
4 answers

std::string PInvoke, ++ ABI , , .. ++.

char* API- C. , PInvoke ++.

+7

, , ++ std::string . ( std::basic_string<char>) ++.

, ++ (, ) . -C-, , ++, ++ #.

, ++ "" ++.

, "" C:

  • , ++ , extern "C" ( ).
  • char* std::string.
  • char* std::string, , .
  • , DllImportAttribute.CallingConvention __cdecl, __stdcall __fastcall C.
+5

, STL string, # , . :

  • ++ char *. -, char * string.
  • ++/CLI- ++, System::String STL-.
+4

If memory is used, unless you specify otherwise, P / Invoke assumes a calling convention __stdcall. If so, a change __cdeclto __stdcallshould fix the first problem. As @Adam Rosenfield points out, you probably also need to transfer and return char const *, not string. C # and C ++ almost certainly have slightly different ideas about what a string is.

+2
source

All Articles