Choose the right way to integrate c++ code

Hello everyone,

I would like to integrate some c++ code to Elixir. The library is https://github.com/online-go/score-estimator.

This is a c++ library with only one functionality, to estimate the score of a go game.

The problem is this is quite expensive (about 500ms).

I learned nif should be short timed functions, otherwise performance will decrease. This is not really the use-case for a port because it is just a command line running.

I have done a wrapper with System, like this

defmodule GoEstimator do
  @moduledoc false
  
  @cmd "#{System.cwd}/priv/estimator"
  
  def estimate(filename) do
    case System.cmd @cmd, [filename] do
      {result, 0} -> 
        {:ok, result}
      {_, code} -> 
        {:error, "could not estimate game, failed with code #{code}"}
    end
  end
end

It is working, but not really useful for communicating with Elixir. I have to create input file, and process stdout.

What would be your advice to integrate c++ simple command line code? With possibly a better data passing between c code and Elixir? Should I?

  • nifs
  • ports/porcelain
  • keep System wrapper, and transform stdin/stdout
  • other not mentionned

Thanks for taking time.

1 Like

I took only a quick look in that repository and it seemed to me as if that project were actually meant to be used as a tool on the command line and not as a library.

So I’d definitifely use it as a CLI tool.

Perhaps file some issues to make the ouput easier to process and to make the tool able to read from STDIN.

Or even better, ask the project to extract a library which makes you then can wrap in a NIF-module, assuming recent enough releases of OTP it shouln’t be a problem as you can use dirty schedulers. You only need to get the hinting right :wink:

3 Likes

Thank You for the answer. I was just a bit concerned about the long running time for a nif.

A C node seems to be missing as an option on that list. Ultimately the level and kind of parallelism you need is going to dictate how hairy that solution would be.

2 Likes