Skip to content

Instantly share code, notes, and snippets.

@am11
Last active August 1, 2020 15:58
Show Gist options
  • Save am11/f21778e56a9984ae37b97d4257fd63ec to your computer and use it in GitHub Desktop.
Save am11/f21778e56a9984ae37b97d4257fd63ec to your computer and use it in GitHub Desktop.
Marshal.PtrToStringUni with non null-terminated string (linux x64)
#!/usr/bin/env sh
gcc -shared -fPIC -o libnullterm.so nullterm.c
LD_LIBRARY_PATH=$(pwd) dotnet run
# output looks like this:
# value: foo1
# length: 4
# value: foo2⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪⨪
# length: 32
// Linux with C11 compiler
#include <stdio.h>
#define DLLEXPORT __attribute__((visibility("default")))
DLLEXPORT
const void* getstrWithNullTerminator(char* in)
{
// foo1
char bytes[] = {0x66, 0x00, 0x6f, 0x00, 0x6f, 0x00, 0x31, 0x00, 0x00, 0x00};
int i = 0;
while (i < 10)
{
*(in + i) = *(bytes + i);
++i;
}
return in;
}
DLLEXPORT
const void* getstrWithoutNullTerminator(char* in)
{
// foo2
char bytes[] = {0x66, 0x00, 0x6f, 0x00, 0x6f, 0x00, 0x32, 0x00};
int i = 0;
while (i < 8)
{
*(in + i) = *(bytes + i);
++i;
}
return in;
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>
</Project>
using System;
using System.Runtime.InteropServices;
unsafe class Program
{
[DllImport("libnullterm")]
private static extern IntPtr getstrWithNullTerminator(byte* inArray);
[DllImport("libnullterm")]
private static extern IntPtr getstrWithoutNullTerminator(byte* inArray);
static void Main()
{
var bytes = new byte[64];
Array.Fill(bytes, (byte)42);
fixed (byte* b = bytes)
{
string x = Marshal.PtrToStringUni(getstrWithNullTerminator(b));
Console.WriteLine("value: {0}\nlength: {1}", x, x.Length);
}
Array.Fill(bytes, (byte)42);
fixed (byte* b = bytes)
{
string x = Marshal.PtrToStringUni(getstrWithoutNullTerminator(b));
Console.WriteLine("value: {0}\nlength: {1}", x, x.Length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment