c++ - Passing a string from a DLL to C# -
i have c# application accesses functions unmanaged c++ libary using cli dll. problem can't text c++ library passed through c# application correctly. code have far follows:
c#
[dllimport("wrapper.dll", entrypoint = "getnamelength", callingconvention = callingconvention = callingconvention.cdecl)] public static extern bool _getnamelength( int index, out int size); [dllimport("wrapper.dll", charset = charset.ansi, entrypoint = "getname", callingconvention = callingconvention.cdecl)] public static extern bool _getname( out stringbuilder name, int size, int index); private void testfunction() { int size = 0; _getnamelength(2, out size); stringbuilder str = new stringbuilder(size + 1); _getname(out str, str.capacity, 2); btnname.text = str.tostring(); }
cli
// in header. #define dllexport __declspec( dllexport) extern "c" { dllexport bool __cdecl getnamelength( int index, int& size); dllexport bool __cdecl getname( char* name, int size, int index); }; // in '.cpp'. bool __cdecl getnamelength( int index, int& size) { if( gp_app == nullptr) return false; gp_app->getnamelength( index, size); return true; } bool __cdecl getname( char* name, int index, int size) { if( gp_app == nullptr) return false; const char* n = ""; n = gp_app->getname( index); name = new char[size]; strcpy( name, n); return true; }
c++
// in header. class app { void getnamelength( int index, int& size); const char* getname( int index); }; // in '.cpp'. void app::getnamelength( int index, int& size) { if( index >= 0 && index < gs_namescount) size = strlen( gs_names[index]); } const char* app::getname( int index) { if( index >= 0 && index < gs_namescount) return gs_names[index]; return nullptr; }
i able debug dll , i've seen copy name on correctly, when use name = const_cast<char*>( n)
(and when use string instead of stringbuilder), reason value isn't getting c# dll.
i read possible reason because c++ may use ascii characters while c# uses 16-bit characters, , fix include charset = charset.ansi
it's marshalled correctly when it's returned c#, apparently hasn't helped.
can tell me i'm doing wrong?
solution:
use public ref class
instead of namespace , declare functions using void foo( [out] string^ %name)
ensuring using namespace system::runtime::interopservices;
included.
this tells me have managed c++ dll.
if( gp_app == nullptr) return false;
if can export managed class , use string parameter method.
check this: http://msdn.microsoft.com/library/windows/apps/hh699870.aspx
Comments
Post a Comment