COMMUNITY

Example of calling Haxe code from Python program?

How I can arrange things in my project such that I can call my own Haxe library code from a Python script?

Thanks!

I realize that I need to first compile my Haxe code to Python, and then access the resulting Python code from Python.

Ah. Ok. I need to back up: How can set up and build my own Haxe library, compiling it to a Python library?

Does this look ok and customary for Haxe?

$ cd ~/dev/my-haxe-libs/my-lib-foo
$ tree -F
.
β”œβ”€β”€ LICENSE.txt
β”œβ”€β”€ py.hxml
β”œβ”€β”€ pylib/
β”‚   └── my_pkg/
β”œβ”€β”€ README.md
└── src/
    └── my_pkg/
        └── MyModule.hx

where my py.hxml file looks like:

-p src
-m my_pkg.MyModule
--python pylib/my_pkg/MyModule.py

and MyModule.hx contains:

package my_pkg;

class MyModule {
    public static function foo() {
        trace("hi");
    }
}

but running haxe py.hxml gives me this error:

$ haxe py.hxml 
src/my_pkg/MyModule.hx:3: lines 3-7 : Invalid -main : my_pkg.MyModule does not have static function main

I don’t have a main because this is a library, but commenting out the β€œ-m” line from py.hxml leaves me with the compiler apparently not happy with it.

Thanks!

Just omit the -m, but keep the rest of the line - you’re not compiling a main class, you want to compile that module.

See also: https://code.haxe.org/category/compilation/compiling-libraries-without-main-class.html

1 Like

Hello,
If you want to export your code as a library, you do not have to define main class.
You can find an example of library export here: https://code.haxe.org/category/compilation/compiling-libraries-without-main-class.html

1 Like

Ooof!! Got it now. Thanks!

Funny. Although my haxe code is in package my_pkg, the resulting Python module is not, but instead the class is named β€œmy_pkg_MyModule”.

Anyhow, it works. Thanks!

On some targets like Python and JS, packages are β€œflattened”, which helps performance a bit. On JS. you can avoid this with -D js-unflatten, doesn’t look like there’s an equivalent for Python.

1 Like