CppSharp icon indicating copy to clipboard operation
CppSharp copied to clipboard

How to transform some generated methods?

Open hellozyemlya opened this issue 2 years ago • 1 comments

Where I can find the examples, how I can alter an output for wrapper function? I have following function I want to use:

char* simpleble_peripheral_identifier(simpleble_peripheral_t handle) {
...
    char* c_identifier = (char*)malloc(identifier.size() + 1);
...
    return c_identifier;
}

The generated output is

      public static sbyte* SimpleblePeripheralIdentifier(__IntPtr handle)
      {
          var __ret = __Internal.SimpleblePeripheralIdentifier(handle);
          return __ret;
      }

But I want to alter such functions to something like:

      public static string SimpleblePeripheralIdentifier(__IntPtr handle)
      {
          var __ret = __Internal.SimpleblePeripheralIdentifier(handle);
          var str = new string(__ret); // not sure, maybe I need to copy all sbyte* to new array before creating string?
          simpleble.SimplebleFree(__ret); // another generated method to free memory allocated for string
          return __ret;
      }

How I can do that?

hellozyemlya avatar Jan 11 '23 08:01 hellozyemlya

The simplest approach would be to add a separate hand maintained partial class where you can just edit the code to your desires and either rename or just ignore this one from generation (use GenerationKind.Internal to keep the internals).

You could also generate the code you want via the generator, either with a decl map, or by using a GeneratorOutputPass but its likely to be more work.

Another interesting approach for this specific case would be signal to CppSharp that the output of simpleble_peripheral_identifier is a dynamically allocated string that needs to be freed and update the generic generation code to support it as such, but it might be hard to do generically due to not knowing exactly which freeing function needs to be called. Anyway, to signal that you could use macros, for instance, like its done in https://github.com/mono/CppSharp/blob/main/src/Generator/Passes/CheckMacrosPass.cs, or by code in some other way if you can't modify the input code.

tritao avatar Jan 11 '23 12:01 tritao