FAQ Database Discussion Community


What is the proper way to go from a String to a *const i8?

rust,ffi
In my ongoing saga of writing a safe wrapper for the Cassandra C++ driver, my eye now turns towards avoiding memory leaks when calling C functions with signatures like: cass_string_init2(const char* data, cass_size_t length); or cass_string_init(const char* null_terminated); I have tried a few different approaches that nominally work, and produce...

Raw pointer type for interior mutable struct

pointers,rust,ffi
I’m doing some Rust FFI work for the Erlang NIF API, and I have these: ErlNifEnv *enif_alloc_env(); void enif_free_env(ErlNifEnv* env); This ErlNifEnv pointer gets passed to a variety of other functions but the user will never deref the pointer. Also, this pointer is not threadsafe (use amongst multiple threads would...

Getting started with purescript

functional-programming,ffi,purescript
I just started learning purescript following purescript by example but I am stuck at the end of Chapter2 using grunt project templates. I follow the instructions, but when I run the grunt command I get this error: /Users/chad/playground/purescript/tests/tmp/node_modules/Control.Monad.Eff.Random/index.js:8 return Math.random(); ^ TypeError: undefined is not a function at Object.random (/Users/chad/playground/purescript/tests/tmp/node_modules/Control.Monad.Eff.Random/index.js:8:17)...

Passing arbitrary-sized integers from Prolog to C

c,prolog,ffi,integer-arithmetic,sicstus-prolog
Right now, I'm learning how to interface SICStus Prolog with C code. I would like to have/use/see a C implementation of "Hamming weight" of arbitrary-sized integers in SICStus Prolog version 4. It seems to me that I need C functions for testing term types (SP_is_integer) and C functions for accessing...

Erlang spawning large amounts of C processes

c,multithreading,lua,erlang,ffi
I've been looking into how I could embed languages (let's use Lua as an example) in Erlang. This of course isn't a new idea and there are many libraries out there that can do this. However I was wondering if it was possible to start a Genserver with state which...

C library freeing a pointer coming from Rust

rust,ffi
I want to do Rust bindings to a C library which requires a callback, and this callback must return a C-style char* pointer to the C library which will then free it. The callback must be in some sense exposed to the user of my library (probably using closures), and...

Calculate distance between two raw pointers

rust,ffi
Some C interfaces return pointer to end of buffer. So then I need to convert the range to a slice. But slice can only be created from pointer and count. So how do I get the count. Writing end - start simply gives me error: binary operation `-` cannot be...

How can I click using ffi in NodeJS?

javascript,windows,node.js,ffi
I am creating a robot for Windows. To move the mouse, this is my code so far: var ffi = require('ffi'), user32 = ffi.Library('user32', { 'SetCursorPos': ['long', ['long', 'long']] });; user32.SetCursorPos(100,100); I need a function that using ffi (or any other way) will click to given coordinates like click(100,100); ...

Python cffi module: does verify() require re-compiling the entire c library I want to use from my python code?

python,python-2.7,ffi,cffi,python-cffi
Say I need to use a few functions from a shared library, e. g. libfoo.so, from python code. I figured the cffi module could help me, especially as it seems to support opaque types if one uses the verify() function. I did not fully understand though, what the documentation means...

Caught between a lifetime and an FFI place

rust,ffi,lifetime
I am caught between two different issues/bugs, and can't come up with a decent solution. Any help would be greatly appreciated Context, FFI, and calling a lot of C functions, and wrapping C types in rust structs. The first problem is ICE: this path should not cause illegal move. This...

hsc2hs: Mutate a C struct with Haskell

c,haskell,types,ffi,hsc2hs
I am trying to write a Haskell program that communicates with C (ultimately for iOS via GHC-iOS). I want it to pass a string from C to Haskell, have Haskell process it and then return some Data types from Haskell to C Structs via hsc2s. I have been unsuccessful at...

Why is bundle --deployment trying to rebuild gem ffi-1.9.6?

ruby-on-rails,ruby,bundler,ffi
I've run bundle --deployment on a machine with a full dev environment, and then copied the vendor/bundle to a second machine not having the full dev environment. On the second machine, a simple 'bundle exec irb' gives: /usr/lib64/ruby/2.1.0/rubygems/ext/builder.rb:89:in `run': ERROR: Failed to build gem native extension. (Gem::Ext::BuildError) /usr/bin/ruby.ruby2.1 extconf.rb mkmf.rb...

Pharo 4 FFI current state and the future

ffi,pharo
I would like to know which FFI interfaces are supported and functional in Pharo 4, which ones are recommended (if any), and if there are some big changes planned in the future Pharo versions. Especially I would like to know which stable FFI callback mechanism is available, and what are...

Adding lifetime constraints to non-reference types

rust,ffi,lifetime
I am trying to figure out how to apply Rust lifetimes to add some compile-time enforcement to Erlang NIF modules. NIF modules are shared libraries normally written in C that provide extensions. A simplified prototype of the callback you would write in C looks like this: Handle my_nif_function(Heap *heap, Handle...

How can I convert a Vec into a C-friendly *mut T?

rust,ffi
I have a Rust library that returns a u8 array to a C caller via FFI. The library also handles dropping the array after the client is done with it. The library has no state, so the client needs to own the array until it is passed back to the...

Create shared C object linked to Rust dylib for use in R

c++,c,r,rust,ffi
I am trying to create a shared object I can load into R that calls Rust functions by way of R's C API. To call Rust from C, I am following this blog post. My problem arises when I try to create the shared library and link to the Rust...

How to lend a Rust object to C code for an arbitrary lifetime?

c,rust,ffi
I'm writing a library in Rust that has a C interface. C side must be able to create and destroy Rust objects (C side owns them and controls their lifetime). I've managed to "leak" an object to C, but I'm not sure how to properly free it: pub extern "C"...

Why doesn't sleep work?

haskell,ghc,ffi
Why does c_sleep return immediately in the following code? {-# LANGUAGE ForeignFunctionInterface #-} import Foreign.C.Types import Data.Time.Clock import Control.Concurrent foreign import ccall unsafe "unistd.h sleep" c_sleep :: CUInt -> IO CUInt main :: IO () main = do getCurrentTime >>= print . utctDayTime c_sleep 10 >>= print -- this doesn't...

How to implement actions in ST-monad with my own underlying representation (similarly to STRef or STArray) using simple techniques?

haskell,ffi,mutable,state-monad
I want to manipulate structs of a certain type from FFI through an interface like that provided with STArray or STRef in an ST monad. I'll have my own specific methods with understandable names for the kind of manipulations that are useful for this struct (like readArray and writeArray for...

Bug in FFI when passing CString followed by an int

windows,rust,32-bit,ffi
My Rust test code extern "C" { fn test_int_only(n : libc::c_int); fn test_int_and_str(s : CString , n : libc::c_int); } pub fn test1() { unsafe { test_int_only(0); test_int_only(1); test_int_only(2); test_int_only(4); test_int_only(-12); } } pub fn test2() { unsafe { test_int_and_str(CString::new("Foo").unwrap(),0); test_int_and_str(CString::new("Bar").unwrap(),1); test_int_and_str(CString::new("Baz").unwrap(),2); test_int_and_str(CString::new("Fub").unwrap(),4); test_int_and_str(CString::new("Bub").unwrap(),-12); } } My C code void...

Integrating Prolog with C#

c#,prolog,ffi,swi-prolog
I am new to Prolog and C#. When I try to integrate Prolog with C# I found some errors, using System; using System.Collections.Generic; using System.Linq; using System.Text; using SbsSW.SwiPlCs; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Environment.SetEnvironmentVariable("SWI_HOME_DIR", @"the_PATH_to_boot32.prc"); // or boot64.prc if (!PlEngine.IsInitialized) { String[]...

How to make C library for ffi during `gem install`

ruby,gem,ffi
Recently I wrote a gem using ffi. With this help, the ruby code can call the C extensions with a dynamic library, which I compile all C extensions into. My gem structure is like this: . ├── ext │   ├── common.c │   ├── common.h │   ├── Makefile │   └── ......

Java-Prolog: How to pass arguments to arity 2 query?

java,prolog,ffi,swi-prolog
I am a beginner level on both Prolog and Java. I am trying to link my Prolog program with Java. I found how to do so here. But I have no idea how to pass the arguments to Prolog query with arity 2. This is a piece of my prolog...

Pass Python list to Rust function

python,rust,ffi
I have a Rust library that needs to be imported into Python via the ctypes module. My goal is to use Rust functions that take Vec<T> / i32 as arguments and return those types, from Python. Currently, I can pass integers to the Rust functions, and have them return lists...

Caching externally-loaded data in a static variable

caching,static,rust,ffi
I'd like to load data from a file, then cache this data (including quite large arrays) in a static variable. This obviously is not the preferred way of doing this, but: I'm writing a Rust library invoked by a C(++) program, and don't currently have any objects which out-live invocation...

Segmentation fault when calling a Rust lib with Ruby FFI

ruby,rust,ffi
I want to pass in a String to a Rust lib, but it always throws a segmentation fault. Here's the code: // lib.rs #[no_mangle] pub extern fn process(foo: String) -> String { foo } And the Ruby file: # embed.rb require 'ffi' module Hello extend FFI::Library ffi_lib 'target/release/libembed.dylib' attach_function :process,...

Linking with a Windows library outside the build folder

windows,rust,ffi
Is there a way to link with a library that's not in the current package path. This link suggests placing everything under the local directory. Our packages are installed in some repository elsewhere. I just want to specify the libpath to it on windows. authors = ["Me"] links = "CDbax"...

How to use FFI:def-call-in in clisp

lisp,common-lisp,ffi,clisp
I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in. I don't know the process and actually I am confused if clisp will also create some .so file that...

Write to file using Lua FFI

file,lua,ffi,luajit
I am trying to use Lua FFI using LuaJIT to append some text to a file, but I am not very knowledgable of C, so I have some trouble. This is the code: local ffi = require "ffi" ffi.cdef[[ typedef int __kernel_ssize_t; typedef __kernel_ssize_t ssize_t; ssize_t write(int fildes, const void...

Pharo 4 FFI async callbacks

smalltalk,ffi,pharo
What are the options (if any) to handle asynchronous FFI callbacks in Pharo 4? By asynchronous I mean that callback gets invoked by foreign language library some time after the FFI function that sets the callback has finished and returned to Smalltalk. Example of NativeBoost callbacks in the image is...

How do I create a storable instance for this structure without c2hs or other tools?

c,haskell,ffi
This structure: typedef struct Atom_ { float x; float y; float z; int col; } Atom; corresponds to this type: data Atom = Atom { pos :: V3 Float, col :: Int } How do I create a storable instance for Atom so that I can send an Atoms on...

Pre-optimize Lua script and call it later from C++

c++,lua,ffi,luajit
I have this filter engine, that I would like to script with LuaJIT, so that I can dump all the complicate parsing/eval code that I have. My filter would be a string like this: function filter ( obj ) return obj.attribute == "toto" I would have something like this in...

LuaJIT: pass pointer to existing 2D array of doubles from C to script?

arrays,pointers,lua,ffi,luajit
I want to manipulate existing 2D arrays of doubles directly in LuaJIT by passing a pointer to the script. I see it isn't possible to create pointers to existing data. Can I pass a pointer to an existing array of primitives from C to LuaJIT and read/write from there? I...

can't pass a newtype-wrapped unsafe C struct without causing illegal instruction

rust,ffi
I am working on wrapping the unsafe FFI layer here, and am running into a very strange problem. (Latest nightly) extern crate cql_ffi; use std::ffi::CString; #[allow(missing_copy_implementations)] pub struct CassCluster(pub cql_ffi::CassCluster); fn main() { let cluster = &mut CassCluster(unsafe{*cql_ffi::cass_cluster_new()}); println!("trying method 1"); let result1 = method1(); println!("trying method 2"); let result2...

What's the right way to create OsStr(ing) from a FFI-returned slice?

rust,ffi
I have a function that accepts a callback with args data: *const u8, length: usize, that represents some path. What is the right way to create an OsStr(ing) from this? There's from_byte_slice in OsStrExt, but seems like it doesn't check if the data is correct WTF-8 or whatever, and it's...

Trouble importing a C function into Haskell

c,haskell,ffi
I have a C program that calls a Haskell function. I want the Haskell function to be responsible for determining the size of the array (pointer) so I also want Haskell to malloc the pointer from C. I get an error when malloc_ is called in Haskell. I am not...

Calling a CUDA “Hello World” from Haskell using the FFI gives wrong results

haskell,cuda,ffi
This is the standard Hello World CUDA file: #include <stdio.h> #include "hello.h" const int N = 7; const int blocksize = 7; __global__ void hello_kernel(char *a, int *b) { a[threadIdx.x] += b[threadIdx.x]; } #define cudaCheckError() { \ cudaError_t e=cudaGetLastError(); \ if(e!=cudaSuccess) { \ printf("Cuda failure %s:%d: '%s'\n",__FILE__,__LINE__,cudaGetErrorString(e)); \ exit(0); \...