Type-checked cfunction call from C++

Hi all,

I’d like to pick up the discussion at https://groups.google.com/d/topic/julia-users/A9HWFVdN4HI/discussion again. To facilitate calling Julia functions from C++, I added some functionality to CxxWrap.jl to make it easier to use jl_call and to add a type check to cfuntion. The basic approach is to wrap the cfunction result in a type like this (constructed using safe_cfunction, with the same signature as used in cfunction):

immutable SafeCFunction
  fptr::Ptr{Void}
  return_type::DataType
  argtypes::Array{DataType,1}
end

On the C++ side, the return and argument types are then checked against the signature of the function pointer. The check happens transparently at the time of conversion, so it is done only once even if the function is called many times. To complete the Google groups discussion, I also benchmarked this and can confirm that the cfunction approach has a much lower overhead than the jl_call approach, as expected:

cfunction in C++ loop
  0.146162 seconds (1.41 k allocations: 61.408 KB)
  0.141575 seconds (4 allocations: 160 bytes)
  0.141625 seconds (4 allocations: 160 bytes)
jl_call inside C++ loop:
  3.3292 seconds (1.00 M allocations: 15.306 MB)
  4.4995 seconds (1.00 M allocations: 15.259 MB, 31.54% gc time)
  7.0557 seconds (1.00 M allocations: 15.259 MB, 56.97% gc time)

Note the tested function here is floating point division, so it is a very small function and the overhead quickly becomes negligible for both approaches when calling functions that do real work.

Comments are welcome, I intend to tag a new CxxWrap with this soon.

2 Likes