c# - Avoiding string allocations on native-to-managed callbacks -
i have native library passes hardware data managed code via callbacks.
basic native-to-managed plumbing done by
[dllimport("library.dll")] public static extern bool init(intptr datacallback) [unmanagedfunctionpointer(callingconvention.stdcall)] public delegate void data(string data); ... var handler = marshal.getfunctionpointerfordelegate(handledata); init(handler); ... private static void handledata(string data) { //use data }
the above works fine.
however, because handledata can called hundreds or thousands of times second (depending on exact hardware module) , data string can quite long, creates noticeable pressure on gc.
avoid creation of strings , instead receive data char[] or byte[] need extract few fields.
tried substitute 'string' stringbuilder or char[] didn't work.
additional information:
- native library passes data char * (null terminated string)
- memory allocated , released native code
- .net version: 4.5
i appreciate help.
thank you!
have tried changing callback signature this?
[unmanagedfunctionpointer(callingconvention.stdcall)] public delegate void data(intptr data); private unsafe static void handledata(intptr data) { byte* charptr = (byte*)data; // work bytes here (which single-byte chars). }
here need cautios , check null character manually.
Comments
Post a Comment