# Type-checked cfunction call from C++

**URL:** <https://discourse.julialang.org/t/type-checked-cfunction-call-from-c/806>\
**Category:** General Usage\
**Created:** [December 8, 2016, 10:17am UTC](https://discourse.julialang.org/t/type-checked-cfunction-call-from-c/806 "2016-12-08T10:17:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![barche](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/barche/32/79_2.png) [@barche](https://discourse.julialang.org/u/barche)\
**Post date:** [December 8, 2016, 10:17am UTC](https://discourse.julialang.org/t/type-checked-cfunction-call-from-c/806/1 "2016-12-08T10:17:57Z")

</div>

Hi all,

I’d like to pick up the discussion at [https://groups.google.com/d/topic/julia-users/A9HWFVdN4HI/discussion](https://groups.google.com/d/topic/julia-users/A9HWFVdN4HI/discussion) again. To facilitate calling Julia functions from C++, I added some [functionality](https://github.com/JuliaInterop/CxxWrap.jl#calling-julia-functions-from-c) 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`):

```julia
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:

```nohighlight
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.
