c2hs bind both typedef and function - c

I am trying to properly create haskell bindings for function in C, that is split up in 2 files.
file1.h: typedef const char* fmi2GetTypesPlatformTYPE(void);
file2.h: __declspec(dllexport) fmi2GetTypesPlatformTYPE fmi2GetTypesPlatform;
To match this in Haskell I have created a similar structure, but this is where the trouble is.
file1.chs: type fmi2GetTypesPlatformTYPE = {#type fmi2GetTypesPlatformTYPE#}
How do I create a Haskell function pointer using this type? I have imported the file with {#import file1 #}, but I am lost on how to accomplish the last part.
See https://github.com/haskell/c2hs/issues/142
I will post the answer once resolved (unless Ian-ross beats me to it :) )

Related

Using multiple Objective-C header files in Swift project

I would like to use the AAPLRendererUtils and AAPLMathUtilities files from the following Apple sample code in a Swift project.
I have created a bridging header where I have imported "APPLMathUtilities.h" and it works just fine. However, when I try to import "AAPLRendererUtils.h" I run into issues.
AAPLRendererUtils.h is a header-only file and does not follow the usual Objective-C #interface and #implementation pattern.
AAPLRendererUtils.h also imports APPLMathUtilities.h so maybe this dependency is an issue?
#import "AAPLMathUtilities.h"
//----------------------------------------------------------------------------------------
struct Camera
{
vector_float3 position;
vector_float3 target;
float rotation;
float aspectRatio; // width/height
float fovVert_Half; // half of vertical field of view, in radians
float distanceNear;
float distanceFar;
matrix_float4x4 GetViewMatrix () const
{
return matrix_look_at_left_hand(position, target, (vector_float3){0,1,0});
}
matrix_float4x4 GetProjectionMatrix_LH () const
{
return matrix_perspective_left_hand (
fovVert_Half * 2.f,
aspectRatio,
distanceNear,
distanceFar);
}
};
Interestingly, if I comment out the function declarations the code runs but if I leave them in I get the following error:
field 'GetViewMatrix' declared as a function
Since you cannot have functions in structs in C am I correct in thinking that Xcode is interpreting this file as a C file?
This is not a C header, it is a C++ header. The files that this gets included in, in the sample document, all have the ".mm" extension which is Objective-C++. C++ does allow structs to have methods (it's basically a class where all the members are public, IIRC). I know a couple of years ago, Swift was not very good at working with C++ files. I don't know if that's changed. You could probably separate the methods from the struct to make a C file and a header if you are diligent enough.

Accessing data from a structure returned by C function in Python using ctypes

I know the subject has already been treated, but I've failed to find anything that works for me, so I guess my problem is slightly different from the others.
What I do, basically, is that I use a C function wrapped into a python code using ctypes.
My goal is to compute some quantities in the C function, store them into a single structure, and return the structure in Python where I could read all the different data in the structure.
So :
To define my structure in python, I use :
class BITE(ctypes.Structure):
_fields_ = [
("lum", ctypes.c_int),
("suce", ctypes.c_int)
]
I compile like that :
sub.call(["gcc","-shared","-Wl,-install_name,ex.so","-o","ex.so","-fPIC","ex.c"])
lum = ctypes.CDLL('ex.so')
lum = lum.lum
I declare the arguments and result types like this :
lum.restype = ctypes.POINTER(BITE)
lum.argtypes = [ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float]
Then, I call the C function "lum" in the python code
out = lum(all the different variables needed)
The problem begins here. I have my structure, but impossible to read the data stored in each fields.
A partial solution I found is to do :
out = out[0]
But then, when doing
print(out.suce)
I have a segmentation fault 11. DOn't know why. I tried to understand how to used create_string_buffer, but I didn't really understand how it works and what it supposed to do. Moreover, I tried to using as a black box, and still, nothing works.
I also tried some other solutions mentionned in other threads such as using out.contents or something like that, but it has no .contents attributes. Nor out.suce.value, which is also something I saw somewhere during my desperate research.
Of course, I checked in the C code that the structure exists and that each field of the structure exists, and has the right data in it.
Thanks.
Suppose you have a C-structure like this :
typedef struct _servParams
{
unsigned short m_uServPort;
char m_pInetAddr[MAX_LENGTH_OF_IP_ADDRESS];
} ServerParams_t;
To use it within ctypes you should create a wrapper like this :
class ServerParams_t(Structure):
_fields_ = [ ("m_uServPort", c_ushort),
("m_pInetAddr", (c_char * 16)) ]
Later on inside your python you can use the following snippet :
servParams = ServerParams_t()
servParams.m_uServPort = c_ushort(int(port))
servParams.m_pInetAddr = ip.encode()
If you need to pass it by value, simply pass servParams variable to you api. If you need to pass a pointer use byref(servParams).

Using Lua FFI with complex types

Bit of a complicated use case... Trying to access a C++ Object inside of Lua FFI, via a C wrapper.
ffi.load("wrapper.so")
​
ffi.cdef[[
struct puppy;
typedef struct puppy puppy_t;
puppy_t * puppy_bark (const char *encoded);
]]
However every time I try to instantiate a puppy, it returns "size of C type is unknown or too large".
I've tried the following to get a puppy created...
pup = ffi.typeof("puppy_t")
pup.puppy_bark("some text")
Results in struct puppy has no member named puppy_bark
pup = ffi.new("struct puppy_t")
pup.puppy_bark("some text")
Returns undeclared or implicit tag
pup = ffi.new("struct puppy puppy_t")
pup.puppy_bark("some stringish thing")
Returns '<eof>' expected near puppy_t
Assuming that the C Wrapper correctly has a Puppy Struct, Type, and the requisite method, how do create an instance of or a pointer to a Puppy in order to make it bark?
Thanks in advance!
You ask "how do I create an instance of or a pointer to a puppy in order to make it bark" - but it's not possible to create an instance of something without having its definition, and it's not possible to create a pointer to something without having an instance of it, and puppies don't bark with your code anyway (but there is a global function puppy_bark that creates a new puppy?).
It looks like you can create a puppy by calling puppy_bark (in which case, what a horribly badly named function!), but I can't be sure of that without seeing the actual code behind puppy_bark.
Since I don't have a specific answer to a specific question, here are some things that are likely to help you:
ffi.new("puppy_t") doesn't work because the FFI needs to have the definition of struct puppy, not just a forward declaration, for exactly the same reason this won't work in C++:
struct puppy;
puppy *p = new puppy;
So, if you want to do this, you need to load the complete definition into the FFI. Note that LuaJIT's FFI only supports C code, not C++.
ffi.new("struct puppy_t") doesn't work because that's not a type that exists.
ffi.new("struct puppy puppy_t") don't work because that's not a valid type.
pup = ffi.typeof("puppy_t") pup.puppy_bark("some text") doesn't work because puppy_bark isn't a member of struct puppy (as the error message tells you).
It also seems like you're misunderstanding the purpose of ffi.typeof. According to the documentation, ffi.typeof returns a constructor for the given type, so that
local new_puppy = ffi.typeof("puppy_t")
local puppy = new_puppy(1, 2, 3, 4)
is the same as
local puppy = ffi.new("puppy_t", 1, 2, 3, 4)
If you want to call the global function puppy_bark, you can do that with ffi.C.puppy_bark("some text").

Make Eclipse list (only) all enum entries on assignment of variable of enum type

The Eclipse <CTRL>+<SPACE> code completion assist feature doesn't work with enums the way I want to. Can anyone tell me how to configure it so that I get the follow:
In my C (not C++) project I'm using typedef enums and would like that Eclipse provides a list of all enum entries on <CTRL>+<SPACE> (or maybe another key combination) if I'm typing an assignment of a variable of this enum type.
Example:
typedef enum {
CONSTANT_A = 0,
CONSTANT_B = 1,
CONSTANT_C = 2,
} myenumtype_t;
void func(void)
{
myenumtype_t myenumvar;
myenumvar = <CTRL>+<SHIFT>
}
It should list CONSTANT_A, CONSTANT_B, CONSTANT_C and allow me to choose one.
If it's list other enum variables of the exact same enum type then this is also ok, but I don't like any other variable in the suggestion list.
However, at the moment my Eclipse is listing basically all global and local variables indendent of their type, which isn't very useful.
PS: My Eclipse variant is Arctic Studio 5.0.0 which is basically Eclipse CDT 8.3.0.
This is not exactly what you asked for, but definitely serves the purpose.
You can type a clue, may be "CON" in your specific case, and then press ctrl + space

Never defined structure

Is there any benefit in having never-defined structures in C ?
Example in SQLite source code :
/* struct sqlite3_stmt is never defined */
typedef struct sqlite3_stmt sqlite3_stmt;
And the object is manipulated like so :
typedef struct Vdbe Vdbe;
struct Vdbe {
/* lots of members */
};
int sqlite3_step(sqlite3_stmt *pStmt) {
Vdbe *v = (Vdbe*) pStmt;
/* do stuff with v... */
}
So why not just use a usual abstract type, with the actual structure privately defined in foo.c source and a public typedef in foo.h header ?
It is defined like this to hide the implementation detail of sqlite3_stmt from the user, thus avoiding the internal states from being messed around. See Opaque pointer.
(This also forces the user only to use the type as a pointer since the structure sqlite3_stmt itself has incomplete implementation.)
Edit: VDBE (virtual database engine) is just "a" back-end of the SQLite3 API. I believe the back-end is changeable, thus a sqlite3_stmt* is not necessarily a Vdbe*. Not exposing Vdbe* in the API because the back-end detail should not be exposed.
To clarify: What you're asking is why SQLite does the above instead of doing this:
Header file:
typedef struct sqlite3_stmt sqlite3_stmt;
C file:
struct sqlite3_stmt {
/* lots of members */
};
int sqlite3_step(sqlite3_stmt *pStmt) {
/* do stuff with pStmt... */
}
(This is the canonical form of the "opaque pointer" pattern linked to in KennyTM's answer.)
The only good reason I can think of why SQLite does what it does is the following:
The backend code, I'm speculating, came before the API and used the name Vdbe -- the name probably means something related to the implementation along the lines of "virtual database entry" (guessing wildly here).
When time came to create the API, someone realized that the parameter required by sqlite3_step was a Vdbe but that this was not exactly a name that would convey a lot to the user of the API. Hence, from the user's point of view, a Vdbe is referred to as an sqlite3_stmt.
The point here, then, is to differentiate between two views of the same item: The backend thinks in terms of Vdbes (whatever they are) because that's a name that makes sense in the context of the implementation. The API talks about sqlite3_stmts because that's a name that makes sense in the context of the interface.
Edit: As Amarghosh points out, why not just do this to achieve the same effect?
typedef struct Vdbe sqlite3_stmt;
KennyTM points out a good possible reason (please vote him up, I don't want to siphon off his rep here): VDBE is only one of several possible backends; the interface uses a "generic" sqlite3_stmt, and this is then cast to whatever the backend uses to implement it.

Resources