I have a native function that will write a string to a buffer provided in the call along with its size. Let’s call it GetFooString(char * str, int strLen)
.
I found out so far that with DllImport
the following would work:
[DllImport("foo.dll", EntryPoint = "GetFooString")]
public static extern void GetFooString(
[MarshalAs(UnmanagedType.LPStr, SizeParamIndex = 1)]
StringBuilder pBuff,
ushort wBuffLen);
There is also this learn.microsoft.com which states that StringBuilder
in P/Invoke should be avoided because of hidden allocations which can hurt performance. The workaround is to do the Marshalling manually by hand.
Since there is source generators based P/Invoke now I figured I can try and use that(compile time generated interop code should have better performance than what DllImport
was doing). If I substitute DllImport
with LibraryImport
the error is that StringBuilder
is not supported in source generated P/Invoke with the same MarshallAsAttribute
as in the DllImport
example. What is the correct way of calling such function with LibraryImport
? Is there a way that would write to a stack allocated Span<char>
which I can then convert to a string or do anything I could do with a Span?