Archived OpenModelica forums. Posting is disabled.

Alternative forums include GitHub discussions or StackOverflow (make sure to read the Stack Overflow rules; you need to have well-formed questions)


Forgot password? | Forgot username? | Register

How to call an external C function?

How to call an external C function?

I've seen many examples on how to implement it and it seems so simple, but every time I try to run an external function written in C an error happens.
My goal is to apply it on a predictive control system, but first I'd like to do an simple example to learn how to do it. Can someone help me?

I've tried this example:

class ChirpSignal

  Modelica.Blocks.Interfaces.RealOutput u;
  parameter Modelica.SIunits.AngularVelocity w_start=0;
  parameter Modelica.SIunits.AngularVelocity w_end=10;
  parameter Real A=1;
  parameter Real M=10;
equation
  u=Chirp(w_start, w_end, A, M, time);

end ChirpSignal;

With the Chirp function being:

function Chirp

input Modelica.SIunits.AngularVelocity w_start;
input Modelica.SIunits.AngularVelocity w_end;
input Real A;
input Real M;
input Real t;
output Real u "output signal";
external "C" annotation(Include="#include \"Chirp.c\"");

end Chirp;

And the .c file as:

double Chirp(double w1, double w2, double A, double M, double time)
{
double res;
res=A*w1*w2*M*time;
return res;
}

The error is as shown bellow:
https://drive.google.com/file/d/1AqUfquOGoU07RwUqfP87ZkqckiFR9Jqe/view?usp=sharing

I'm not using a header file, but already tried to use it. What should I do?

Thank you!

Re: How to call an external C function?

Where did you put the file? The only location that is searched is Teste26-02/Resources/Include

Re: How to call an external C function?

You can use also other directories if you include them, as follows:

package ChirpP
  class ChirpSignal
    Modelica.Blocks.Interfaces.RealOutput u;
    parameter Modelica.SIunits.AngularVelocity w_start = 1;
    parameter Modelica.SIunits.AngularVelocity w_end = 10;
    parameter Real A = 1;
    parameter Real M = 10;
  equation
    u = Chirp(w_start, w_end, A, M, time);
  end ChirpSignal;

  function Chirp
    input Modelica.SIunits.AngularVelocity w_start;
    input Modelica.SIunits.AngularVelocity w_end;
    input Real A;
    input Real M;
    input Real t;
    output Real u "output signal";
 
    external "C"  annotation(
      IncludeDirectory = "modelica://ChirpP",
      Include = "#include \"Chirp.c\"");
  end Chirp;
end ChirpP;

"modelica://ChirpP" will place you in the directory where ChirpP package is, and you can put the c file there. Or indicate a relative path, for example:  IncludeDirectory = "modelica://ChirpP/Resources" and put the C files in Resources, that is the default.

I have changed w_start from 0 to 1, because if it 0 the result is always 0.

Re: How to call an external C function?

It worked! Thank you!

There are 0 guests and 0 other users also viewing this topic
You are here: