tags:

views:

38

answers:

2

Using VS2008 Managed C++ to wrap a dll. The native method takes a series of single const char* values and a collection of char* values. Going to make an example function:

Function1(char * value1, TF_StringList& catList);  

TF_StringList is a dll class with 3 insert methods, the one I want to use is:

TF_StringList::insert(const char* str);  

So I set up a wrapper method of:

WrapperClass::callFunction(String^ mvalue1, ArrayList mcatList);  

mvalue1 is converted to const char* using:

const char* value1 = (char*)(Marshal::StringToHGlobalAnsi(mvalue1)).ToPointer();  

However, when a get to the collection of strings, I iterate over it getting each string using the index:

String^ mstr = mcatList[i];  

Have tried every way of converting String^ to const char* and in every case the TF_StringList::insert(const char* str) method throws a C2663 error which has to do with the const-ness of the value. What is the problem?

+1  A: 

Your code snippets are not helpful, they cannot compile as given and don't show the real source of the error. Review the MSDN Library docs for C2663, it doesn't have anything to do with the argument. The object pointer is the problem.

Beware that your StringToHGlobalAnsi() call as posted is a memory leak. You have to call Marshal::FreeHGlobal() on the returned IntPtr after you're done with the string. Somebody is going to have to copy it.

Hans Passant
Given that the error is thrown on the non-const function call insert(const char* str), the "this" pointer that it is complaining about is str. My question is how do I get the string coming out of the ArrayList to be the "const char*" that the insert function is looking for?I am fully aware that the char* pointer needs to be cleaned up, however it is only necessary to clean up what you have successfully created. Right now I'm having problems getting thing created.My research indicates that the link you posted covers only one cause for C2663.
Jim Jones
The "this" pointer is not str. I recommend you post real code that can repro this compile error.
Hans Passant
Owe you an apology, the this pointer it was complaining about is the instance pointer of TF_StringList which I declared as const, instantiated, and tried to add strings to via the insert method. Removed the const modifier and it worked fine. Thanks
Jim Jones
@Jim: no need to apologize, around here you say sorry by upvoting helpful answers.
Hans Passant
A: 

include

#include <vcclr.h>

then in a scope

{
    String^ s = gcnew String("test string");
    pin_ptr<const wchar_t> str = PtrToStringChars(s);

    size_t origsize = wcslen(orig) + 1;
    const size_t newsize = 100;
    size_t convertedChars = 0;
    char nstring[newsize];
    wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE);

    CallFunction(&nstring);
}

The important part is pinning the pointer so that it doesn't get relocated on you in a garbage collection.

LukeN