unsafe
[Rubyist Magazine - C# と Ruby を連携させる]
上のページはありがたかった。ただ、unsafeを使っているところがある。そこは、unsafeを使わないでも書ける。
"public static string StringValuePtr(VALUE v)"でunsafeを使っている。
unsafe { byte* p = (byte*)ptr; // (4) while (*p != 0) // (5) { length++; p++; } }
ここの場合は、Kernel32.dllのlstrlenA()を呼び出すようにすれば、unsafeを使わなくてもすむ。
class Win32 { [DllImport("kernel32", EntryPoint = "lstrlenA")] public static extern int lstrlenA(IntPtr s); }
をどこかに定義しておく。
length = Win32.lstrlenA(ptr);