C++/CLI LoadLibrary Failing on Converting System::String to LPCWSTR and const char *

Go To StackoverFlow.com

1

Trying to pass in a user supplied string which has a path to the jvm.dll but it doesn't load the library unless I hard code with the following:

#define RUNTIME_DLL _T("C:\\Program Files\\Java\\jre7\\bin\\Server\\jvm.dll")

It compiles but fails if I try this:

HINSTANCE handle = LoadLibrary((const char*)Marshal::StringToHGlobalAnsi(string).ToPointer());

The "string" var has the exact copy and pasted path that _T() has but still fails. Not an expert in C/C++ so I'm not sure what _T() gets it to work.

Update:

Tried this:

// System::String always stored as Unicode, get a Unicode pointer with no conversion necessary
        pin_ptr<const WCHAR> lib_name = PtrToStringChars(string);
        // Always use the Unicode version of LoadLibrary
        HINSTANCE handle = LoadLibraryW(lib_name);

And still it won't load the jvm.dll file. It will only load it if I do this:

#define RUNTIME_DLL _T("C:\\Program Files\\Java\\jre7\\bin\\Server\\jvm.dll")

        // System::String always stored as Unicode, get a Unicode pointer with no conversion necessary
        pin_ptr<const WCHAR> lib_name = PtrToStringChars(RUNTIME_DLL);
        // Always use the Unicode version of LoadLibrary
        HINSTANCE handle = LoadLibraryW(lib_name);

Tried this as well:

        // System::String always stored as Unicode
        marshal_context^ ctx = gcnew marshal_context();
        pin_ptr<const WCHAR> lib_name = PtrToStringChars(jvmDllPath);           
        //const wchar_t * lib_name = ctx->marshal_as<const wchar_t*, System::String^>(jvmDllPath);
        printf("JVM Path: %s", lib_name);
        // Always use the Unicode version of LoadLibrary
        handle = LoadLibraryW(lib_name);            

        if( handle == 0) {
            printf("Failed to load jvm dll \n");
            //printf(ErrorExit((LPTSTR)(const char*)"Initialize"));
                            // this is the part that will work
            System::String^ string = gcnew System::String("C:\\Program Files\\Java\\jre7\\bin\\Server\\jvm.dll");
            pin_ptr<const WCHAR> lib_name = PtrToStringChars(string);
            handle = LoadLibraryW(lib_name);
        }
        delete ctx;  // do this for now to not create memory leaks

The C++/CLI method signature is:

void Initialize(String^ jvmDllPath)

The body is basically the code above

The C# code that calls into this with a string parameter is this:

obj.Initialize("c:\\program files\\java\\jdk7\\jre\\bin\\server\\jvm.dll");

Providing answer here from Ben's suggestion so people/newbs and temporary c/c++/cli coders can find a quick answer to avoid what I went through:

    const char * CliToNativeString(String^ cliString){
        const char * converted;
        converted = (gcnew marshal_context())->marshal_as<const char *>( cliString );           
        return converted;
    }

    String^ NativeToCliString(const char * nString){
        String^ converted = gcnew String("");
        if(nString != NULL)
            converted = (gcnew marshal_context())->marshal_as<String^>(nString); 
        return converted;
    }
2012-04-05 01:33
by bbqchickenrobot
I've also replaced the (const char *) cast with (LPCWSTR) and it compiles but still fails.... very odd - bbqchickenrobot 2012-04-05 01:34
Yes, casting will force your code to compile. That doesn't make it correct, or even require that it make any sense. If you write code that doesn't work, start by eliminating all of the casts and following the error diagnostics emitted by your compiler - Cody Gray 2012-04-05 02:27
I'm aware but since working with C++/CLI casting is required so that ain't it. Thanks though - bbqchickenrobot 2012-04-05 02:42
No, there's no rule that casting is required for C++/CLI. The only thing casting is "required" for is masking bugs - Cody Gray 2012-04-05 02:43
I have to cast as a variable of type String^ cannot be passed to LoadLibrary() unless I am missing something. Basically this is managed wrapper that is called/used/invoked by a C# program which passes in a type System::String to the C++/CLI wrapper. I must then cast this to a C style string for LoadLibrary() to work. If I'm mistaken I would appreciate any pointers (no pun intended) - bbqchickenrobot 2012-04-05 03:02
That's precisely my point. A cast just makes the compiler shut up, it doesn't actually perform the conversion that you need. The System::String managed type is not the same thing as the unmanaged C-style string, which is what the LoadLibrary() function is expecting. LoadLibrary() is a native Win32 API function that has absolutely no knowledge of .NET stuff like the System::String class. You have to do more than perform a cast; you have to actually convert. Ben's answer has what you need, and so does this MSDN article - Cody Gray 2012-04-05 03:04
A cast is just a way of telling the compiler, "I know what I'm doing, trust me". Sometimes that's what you want, but very rarely. And when it is what you want, you need to make sure that you document that very carefully. Lots of programmers hide mistakes by throwing in casts instead of understanding why the compiler is throwing that error and trying to use the diagnostics it provides to fix the problem. Any time I see a cast who use isn't carefully documented with a comment, I immediately consider it suspect - Cody Gray 2012-04-05 03:06
@Cody: That series of examples on MSDN is terrible. Point people to this overview and this example instead - Ben Voigt 2012-04-05 03:08
cool, thanks ... forgot that casts in C++ don't quite work like C#. Ok, will try the two methods in Ben's post. THanks guys. Got a deadline to meet! : - bbqchickenrobot 2012-04-05 03:11
The C# code uses "jdk7\jre", but the C++/CLI test constant has "jre7 - Ben Voigt 2012-04-05 04:10
BTW that's not how marshal_context is meant to be used. Oh darn, you got it from the example I referenced. Stack semantics FTW, they're C++/CLI's version of C# using blocks, but much much nicer. Anyway, marshal_context isn't needed when you are using PtrToStringChars - Ben Voigt 2012-04-05 04:13
Your final version is using strings after their memory has been freed. I really suggest the technique shown in my answer, but if you do use marshal_as with a marshal_context, make sure the marshal_context lives long enough - Ben Voigt 2014-05-04 20:51


3

There are better ways for getting a C-style string from a System::String^. Have a look at the marshal_as and marshal_context templates supplied with VC++.

Your immediate problem here is that you are compiling for Unicode, so LoadLibrary requires a unicode string, but StringToHGlobalAnsi does not return a unicode string. No amount of pointer casting will change the encoding of the string pointed to.

You also have a memory leak.

Try this instead:

#include <vcclr.h>

// System::String always stored as Unicode, get a Unicode pointer with no conversion necessary
pin_ptr<const WCHAR> lib_name = PtrToStringChars(string);
// Always use the Unicode version of LoadLibrary
HINSTANCE handle = LoadLibraryW(lib_name);

If this works and the above doesn't, then something is wrong with the string sent from C#:

System::String^ string = gcnew System::String(L"C:\\Program Files\\Java\\jre7\\bin\\Server\\jvm.dll");
pin_ptr<const WCHAR> lib_name = PtrToStringChars(string);
HINSTANCE handle = LoadLibraryW(lib_name);
2012-04-05 02:24
by Ben Voigt
Thanks for the help tried your method and it sill has the same issues. I also tried with the methods in the updated post. Very weird IMO - bbqchickenrobot 2012-04-05 02:56
@bbqchickenrobot: Which of the issues do you still have? Is it a compile error (show the message) or a runtime error? What is the value of string - Ben Voigt 2012-04-05 03:01
BTW, the _T makes either an ANSI string or a Unicode string, depending on your compile settings. Since you are compiling for Unicode, L"jvm.dll" would give you the same effect. You don't actually have any double backslashes in the string, right, only in the code that makes the string - Ben Voigt 2012-04-05 03:04
Runtime error... the LoadLibrary() returns NULL. But the code runs & compiles w/o problems. Wehn I substitute the #define RUNTIME_DLL it runs fine... and actually loads the jvm.dll file and the program works perfectly. And yes, I don't have any double backslashes - verified that it shows as c:\program files...\jvm.dll in the variables during debug - bbqchickenrobot 2012-04-05 03:06
@bbqchickenrobot: Try this version (it was messed up momentarily, should be ok now) - Ben Voigt 2012-04-05 03:09
Added the "\0" to end of strings in both C# and C++ code and LoadLibrary() still returned NULL. When I add your code right after my code fails - (ur 2nd code block) using gcnew string it works perfectly and loads the library. Not sure what could be wrong with the C# strings. I added the "\0" to the end of those too but no success - bbqchickenrobot 2012-04-05 03:57
Ads