Tyler Durden
Tyler Durden

Reputation: 1228

C# Equivalent for PtrToStringChars(String s) function present in vcclr.h

I have a native C++ function which I wish to import into my C# project file.

the file is vcclr.h and its present in Visual Studio 9.0/VC/include folder. The function is PtrToStringChars(string s)

Is there an equivalent c# function I can use in place of this native C++ function?

Also, if I wish to import this function I need to specify the name of the dll which contains this file. How do I get the name of this dll?

I can see the C++ file containing this function and from there I can see its folder location (absolute and relative path).

Upvotes: 0

Views: 711

Answers (1)

xanatos
xanatos

Reputation: 111910

You don't need that method:

string str = "hello".Substring(0, 2); // force not to inline the string
                                      // it would be the same if it was inlined

GCHandle h = GCHandle.Alloc(str, GCHandleType.Pinned);
IntPtr ptr = h.AddrOfPinnedObject(); // Your address

// ch is h
// the unchecked is necessary (technically optional because it's default)
// because Marshal.ReadInt16 reads a signed Int16, while char is more similar
// to an unsigned Int16
char ch = unchecked((char)Marshal.ReadInt16(ptr));

or with a little unsafe code (see fixed Statement):

fixed (char* ptr2 = str)
{
    char ch2 = *ptr2;
}

And what if you want exactly PtrToStringChars(...)? You can't have it... It's defined directly in the vcclr.h header as an inline function (in mine lines 37-39 for comments, 40-48 for code).

Upvotes: 3

Related Questions