# Testing C functions with Julia

**URL:** <https://discourse.julialang.org/t/testing-c-functions-with-julia/2435>\
**Category:** General Usage\
**Tags:** question\
**Created:** [March 4, 2017, 12:04pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435 "2017-03-04T12:04:59Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 12:04pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/1 "2017-03-04T12:04:59Z")

</div>

Hello,  
I want to use Julia to write unit tests for C functions.  
How can I do this?  
Example of a C function:

```nohighlight
#include "../include/mixer.h"

void mixer(REAL32 total_thrust, REAL32 delta_thrust, struct actuator_output *output)
{
	/* Calculate a desired thrust for each motor */
	double th1 = total_thrust + 0.5 * delta_thrust;
	double th2 = total_thrust - 0.5 * delta_thrust;
	
	/* Limit the desired thrust value */
	if (th1 > 1.0) th1 = 1.0;
	if (th1 < MIN_THRUST) th1 = MIN_THRUST;
	output->back_motor = th2;
	
	if (th2 > 1.0) th1 = 1.0;
	if (th2 < MIN_THRUST) th2 = MIN_THRUST;
	output->front_motor = th2;
}

```

Header file:

```julia
#ifndef MIXER_H_
#define MIXER_H_

#define MIN_THRUST 0.02

typedef float REAL32;

struct actuator_output {
	REAL32 front_motor;
	REAL32 back_motor;
};

void mixer(REAL32 total_thrust, REAL32 pid_out, struct actuator_output *output);

#endif

```

Script to compile the code to an .so file (is this needed?):

```julia
gcc -c -fPIC src/mixer.c -o mixer.o
gcc -shared -fPIC -Wl,-soname,libmixer.so.1 -o libmixer.so.1.0.1 mixer.o -lc

```

After running this script I have a file libmixer.so.1.0.1 , but how do I now call  
this function from Julia?  
And is it necessary to create a shared object file, or can Julia call c functions  
in a more easy way?

---

<div class="post-metadata">

**Author:** ![KajWiik](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kajwiik/32/199_2.png) [@KajWiik](https://discourse.julialang.org/u/KajWiik)\
**Post date:** [March 4, 2017, 1:15pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/2 "2017-03-04T13:15:03Z")

</div>

I think everything you need is here:  
[http://docs.julialang.org/en/release-0.5/manual/calling-c-and-fortran-code/](http://docs.julialang.org/en/release-0.5/manual/calling-c-and-fortran-code/)

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 2:39pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/3 "2017-03-04T14:39:29Z")

</div>

Thanks for the hint!

I have now the following code:

```julia
println("Testing mixer.c ...")

#=
struct actuator_output {
	REAL32 front_motor;
	REAL32 back_motor;
};

void mixer(REAL32 total_thrust, REAL32 pid_out, struct actuator_output *output);
=#

type Actuator_output
    front_motor::Float32 # electrical generator power in kW
    back_motor::Float32 # ratio of the drum diameter and the tether diameter
end

total_thrust = Float32(0.5)
pid_out = Float32(0.1)

output = Actuator_output(0.0, 0.0)

ccall(:mixer, "lib/libmixer.so", (total_thrust, pid_out, output))

println(output)

```

But executing it gives the following error:

```julia
ufechner@TUD277255:~/uavtalk$ ./test_mixer.sh 
Testing mixer.c ...
ERROR: LoadError: TypeError: ccall: expected Type{T}, got String
 in include_from_node1(::String) at ./loading.jl:488
 in process_options(::Base.JLOptions) at ./client.jl:262
 in _start() at ./client.jl:318
while loading /home/ufechner/uavtalk/scripts/test_mixer.jl, in expression starting on line 22

```

Any idea?

---

<div class="post-metadata">

**Author:** ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)\
**Post date:** [March 4, 2017, 2:51pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/4 "2017-03-04T14:51:40Z")

</div>

[http://docs.julialang.org/en/release-0.5/manual/calling-c-and-fortran-code/](http://docs.julialang.org/en/release-0.5/manual/calling-c-and-fortran-code/)

1. (:function, “library”) pair (must be a constant, but see below).
2. Return type (see below for mapping the declared C type to Julia)
  - This argument will be evaluated at compile-time.

3. A tuple of input types. The input types must be written as a literal tuple, not a tuple-valued variable or expression.

- This argument will be evaluated at compile-time.

1. The following arguments, if any, are the actual argument values passed to the function.

I think you are missing both two and three. Start from working example:

```julia
function gethostname()
  hostname = Array{UInt8}(128)
  ccall((:gethostname, "libc"), Int32,
        (Ptr{UInt8}, Csize_t),
        hostname, sizeof(hostname))
  hostname[end] = 0; # ensure null-termination
  return unsafe_string(pointer(hostname))
end

```

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 2:59pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/5 "2017-03-04T14:59:08Z")

</div>

Ok, but the return type is void . So what is the equivalent in Julia?

---

<div class="post-metadata">

**Author:** ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)\
**Post date:** [March 4, 2017, 3:10pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/6 "2017-03-04T15:10:03Z")

</div>

> [@ufechner7](#):
>
> Ok, but the return type is void . So what is the equivalent in Julia?

[http://docs.julialang.org/en/release-0.5/manual/calling-c-and-fortran-code/#creating-c-compatible-julia-function-pointers](http://docs.julialang.org/en/release-0.5/manual/calling-c-and-fortran-code/#creating-c-compatible-julia-function-pointers)

```julia
A = [1.3, -2.7, 4.4, 3.1]
ccall(:qsort, Void, (Ptr{Cdouble}, Csize_t, Csize_t, Ptr{Void}),
      A, length(A), sizeof(eltype(A)), mycompare_c)

```

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 3:24pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/7 "2017-03-04T15:24:13Z")

</div>

Ok, this is what I get now. Code:

```julia
println("Testing mixer.c ...")

#=
struct actuator_output {
	REAL32 front_motor;
	REAL32 back_motor;
};

void mixer(REAL32 total_thrust, REAL32 pid_out, struct actuator_output *output);
=#

type Actuator_output
    front_motor::Float32 # electrical generator power in kW
    back_motor::Float32 # ratio of the drum diameter and the tether diameter
end

total_thrust = Float32(0.5)
pid_out = Float32(0.1)

output = Actuator_output(0.0, 0.0)

ccall((:mixer, "lib/libmixer.so"), Void, (Float32, Float32, Ptr(Actuator_output)), total_thrust, pid_out, output)

println(output)

```

Error message:

```julia
Testing mixer.c ...
ERROR: LoadError: MethodError: Cannot `convert` an object of type Type{Actuator_output} to an object of type Ptr{T}
This may have arisen from a call to the constructor Ptr{T}(...),
since type constructors fall back to convert methods.
 in anonymous at ./<missing>:?
 in include_from_node1(::String) at ./loading.jl:488
 in process_options(::Base.JLOptions) at ./client.jl:262
 in _start() at ./client.jl:318
while loading /home/ufechner/uavtalk/scripts/test_mixer.jl, in expression starting on line 22

```

Any idea?

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 4:11pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/8 "2017-03-04T16:11:05Z")

</div>

Ok, I fixed it:

```julia
println("Testing mixer.c ...")

#=
struct actuator_output {
	REAL32 front_motor;
	REAL32 back_motor;
};

void mixer(REAL32 total_thrust, REAL32 pid_out, struct actuator_output *output);
=#

type Actuator_output
	front_motor::Float32
	back_motor::Float32
end

total_thrust = Float32(0.5)
pid_out = Float32(0.1)

output = Ref(Actuator_output(0.0, 0.0))

ccall((:mixer, "lib/libmixer.so"), Void, (Float32, Float32, Ref{Actuator_output}), total_thrust, pid_out, output)

println(output.x)

```

An example like this should be added to the manual. I found some hints how to do this on stack overflow, but it is not explained in the manual:

> <https://stackoverflow.com/questions/30561521/passing-a-pointer-to-struct-as-an-argument-in-julia>

---

<div class="post-metadata">

**Author:** ![dpsanders](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dpsanders/32/3573_2.png) [@dpsanders](https://discourse.julialang.org/u/dpsanders)\
**Post date:** [March 4, 2017, 4:16pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/9 "2017-03-04T16:16:09Z")

</div>

A Pull Request to the manual would be very welcome.

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [March 4, 2017, 4:57pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/10 "2017-03-04T16:57:45Z")

</div>

> [@ufechner7](#):
>
> Ref(Actuator\_output(0.0, 0.0))

You don’t need the `Ref`. This is already covered in the table entry for `T*` which stated that you just need to use `Ref{T}` as argument type and nothing else.

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 10:03pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/11 "2017-03-04T22:03:49Z")

</div>

Thanks for the info.  
For the record: Today I wrote 16 unit tests in Julia for my C code and found and fixed more than one non-trivial bug in my C code. Julia provides efficient means to write tests for C functions. 🙂  
Uwe

---

<div class="post-metadata">

**Author:** ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)\
**Post date:** [March 4, 2017, 10:32pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/12 "2017-03-04T22:32:18Z")

</div>

> [@ufechner7](#):
>
> Julia provides efficient means to write tests for C functions

OT: why you need to develop using C code? Why can’t you write it in Julia?

---

<div class="post-metadata">

**Author:** ![ufechner7](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ufechner7/32/51363_2.png) [@ufechner7](https://discourse.julialang.org/u/ufechner7)\
**Post date:** [March 4, 2017, 11:02pm UTC](https://discourse.julialang.org/t/testing-c-functions-with-julia/2435/13 "2017-03-04T23:02:43Z")

</div>

Well, currently I am writing security critical, real-time flight control software for very small embedded systems. Julia is not a good choice for this kind of applications.
