Skip to content

Instantly share code, notes, and snippets.

@larsiusprime
Created May 26, 2017 20:31
Show Gist options
  • Save larsiusprime/a179d905e6f9a4fa4722518d2be7ad58 to your computer and use it in GitHub Desktop.
Save larsiusprime/a179d905e6f9a4fa4722518d2be7ad58 to your computer and use it in GitHub Desktop.

How do I get string content from Haxe to an untyped cpp block?

static public function haxeFunction(inputString:String)
{
  untyped __cpp__ ('
  
      myStruct myFoo;       
      myFoo.data = ???;   //Should be the string contents of Haxe String inputString (1st 16 characters, ASCII only is fine)
        
  ');
}

Definition of myStruct:

typedef struct myStruct {
    char data[16];
} myStruct;
@ibilon
Copy link

ibilon commented May 26, 2017

var s:cpp.ConstCharStar = inputString;
untyped __cpp__ ('myStruct myFoo;');
for (i in 0...inputString.length) {
  untyped __cpp__ ('myFoo.data[{0}] = {1}[{0}]', i, s);
}

@hughsando
Copy link

// For '.c_str()'
using cpp.NativeString;

@:structAccess
extern class MyStruct
{
   // Decalare as raw pointer, even though it has a buffer associated with it
   // I would prefer to declare this as cpp.Star<cpp.Char>, but Stdlib.memcpy needs fixing
   public var foo:cpp.Pointer<cpp.Char>;
   public function printMe():Void;

   @:native("MyStruct") // Pseudo-constructor
   public static function create():MyStruct;
}
@:cppFileCode('

struct MyStruct
{
   char foo[100];

   void printMe() { printf("foo:%s\\n", foo); } // double back-slash for haxe meta string quoting
};
')
class Test
{
   public static function main()
   {
      // Avoid 'Local variable myStruct used without being initialized'
      var myStruct = MyStruct.create();

      var myData = "bar";

      cpp.Stdlib.memcpy( myStruct.foo, myData.c_str(), myData.length + 1); // +1 for null-termination

      myStruct.printMe();
      
   }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment