I'm working in C# with a Borland C API that uses a lot of byte pointers for strings. I've been faced with the need to pass some C# strings as (short lived) byte*.

It would be my natural assumption that a const object would not be allocated on the heap, but would be stored directly in program memory, but I've been unable to verify this in any documentation.

Here's an example of what I've done in order to generate a pointer to a constant string. This does work as intended in testing, I'm just not sure if it's really safe, or it's only working via luck.

private const string pinnedStringGetWeight = "getWeight";

unsafe public static byte* ExampleReturnWeightPtr(int serial)
{
    fixed (byte* pGetWeight = ASCIIEncoding.ASCII.GetBytes(pinnedStringGetWeight))
        return pGetWeight;
}

Is this const really pinned, or is there a chance it could be moved?


@Kragen:

Here is the import:

[DllImport("sidekick.dll", CallingConvention = CallingConvention.Winapi)]
public static extern int getValueByFunctionFromObject(int serial, int function, byte* debugCallString);

This is the actual function. Yes, it actually requires a static function pointer:

 private const int FUNC_GetWeight = 0x004243D0;

 private const string pinnedStringGetWeight = "getWeight";

 unsafe public static int getWeight(int serial)
 {
     fixed (byte* pGetWeight = ASCIIEncoding.ASCII.GetBytes(pinnedStringGetWeight))
         return Core.getValueByFunctionFromObject(serial, FUNC_GetWeight, pGetWeight);
 }

Following is another method that I used when mocking my API, using a static struct, which I also hoped was pinned. I was hoping to find a way to simplify this.

public byte* getObjVarString(int serial, byte* varName)
{
    string varname = StringPointerUtils.GetAsciiString(varName);
    string value = MockObjVarAttachments.GetString(serial, varname);
    i
Edit
Report