D struct with String type accessing from Python

cc cc at nevernet.com
Mon Dec 26 04:41:12 UTC 2022


On Monday, 26 December 2022 at 03:05:33 UTC, alchemypy wrote:
> Can you please help me what went wrong here ?

I tried to do something similar in C# once.  Internally, I 
believe D stores the size of a slice before the pointer.

Not sure if this will help, I abandoned this idea after playing 
with it for a while.  I think I had trouble getting the D 
compiler to send one of its own strings/slices to an extern(C) 
function.  I believe it worked fine if I sent the string result 
AS a struct that separated out the size and pointer, but failed 
for unexplained reasons if I just tried to send the basic 
string/immutable(char)[] as-is.

```C#
// C#
		[StructLayout(LayoutKind.Sequential, Size=16, Pack=1)]
		public struct DString {
			public ulong length;
			public IntPtr ptr;
			public string str {
				get {
					byte[] b = new byte[length];
					for (int i = 0; i < (int)length; i++) {
						b[i] = Marshal.ReadByte(ptr, i);
					}
					return Encoding.UTF8.GetString(b);
				}
			}
		}
		[DllImport("mydll.dll")]
		private static extern void DDLL_testString(out DString dd);
		public static string testString() {
			DString d;
			DDLL_testString(out d);
			return d.str;
		}
```
```d
// D DLL
static struct DString {
	size_t length;
	immutable(char)* ptr;
	this(string str) {
		length = str.length;
		ptr = str.ptr;
	}
	void opAssign(string str) {
		length = str.length;
		ptr = str.ptr;
	}
}
//extern(C) export DString testString() {
extern(C) export void testString(out string ret) {
	string str = "hello王".idup;
	//return DString(str);
	ret = str;
}
```



More information about the Digitalmars-d mailing list