开发者

Converting String^ and Collection of String^ to const char*

Using VS2008 Managed C++ to wrap a dll. The nati开发者_开发百科ve 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜