How to pass pointer to slice to C function in go - c

Background: using cgo to call C functions from Golang.
I want to use a C function which has this signature: int f(int *count, char ***strs).
It will modify the data of count and strs, which is the reason why it uses pointer to them.
The value of count is the length of strs; strs is an array of string; the return value is simply an (boolean) indicator which states whether there is an error or not.
In golang, I can successfully pass and modify count by using C.f((*C.int)(&count)); pass []string by using []*C.char. Sample code is like this:
/*
#include <stdio.h>
int f(int *c, char **str) {
int i;
printf("%d\n", *c);
for (i = 0; i < *c; i++) {
printf("%s\n", str[i]);
}
*c = (*c) + 1;
return 1;
}
*/
import "C"
func go_f(strs []string) int {
count := len(strs)
c_count := C.int(count)
c_strs := make([]*C.char, count)
for index, value := range strs {
c_strs[index] = C.CString(value)
defer C.free(unsafe.Pointer(c_strs[index]))
}
err := C.f(&c_argc, (**C.char)(&c_argv[0]))
return int(err)
}
As you can see, the C function is currently int f(int *c, char **str), but what I'd like is int f(int *c, char ***str).
This is to say: what I actually want is to enable the modification to the string array (e.g. resize) in C and turn it back to a Go string slice so I can still use it in Go.
How to do this? I've searched and experimented for a while but with no luck.

A Go slice is both allocated in Go, and a different data structure than a C array, so you can't pass it to a C function (cgo will also prevent you from doing this because a slice contains a Go pointer)
You need to allocate the array in C in order to manipulate the array in C. Just like with C.CString, you will also need to track where to free the outer array, especially if the C function may possibly allocate a new array.
cArray := C.malloc(C.size_t(c_count) * C.size_t(unsafe.Sizeof(uintptr(0))))
// convert the C array to a Go Array so we can index it
a := (*[1<<30 - 1]*C.char)(cArray)
for index, value := range strs {
a[index] = C.CString(value)
}
err := C.f(&c_count, (***C.char)(unsafe.Pointer(&cArray)))

Related

Passing a 2D array to a function in C?

I need to pass a 2D array to a function.
#include <stdio.h>
#define DIMENSION1 (2)
#define DIMENSION2 (3)
void func(float *name[])
{
for( int i=0;i<DIMENSION1;i++){
for( int j=0;j<DIMENSION2;j++){
float element = name[i][j];
printf("name[%d][%d] = %.1f \n", i, j, element);
}
}
}
int main(int argc, char *argv[])
{
float input_array[DIMENSION1][DIMENSION2] =
{
{0.0f, 0.1f, 0.2f},
{1.0f, 1.1f, 1.2f}
};
func(input_array);
return 0;
}
Dimensions vary depending on the use case, and the func should stay the same.
I tried the above int func(float *[]) but compiler complains expected ‘float **’ but argument is of type ‘float (*)[3]’, and also I get the segmentation fault error at runtime when trying to access the array at element = name[i][j].
What would be the proper signature of my function? Or do I need to call the func differently?
You can use the following function prototype:
int func(int dim1, int dim2, float array[dim1][dim2]);
For this you have to pass both dimensions to the function (you need this values anyhow in the function). In your case it can be called with
func(DIMENSION1, DIMENSION2, input_array);
To improve the usability of the function call, you can use the following macro:
#define FUNC_CALL_WITH_ARRAY(array) func(sizeof(array)/sizeof(*(array)), sizeof(*(array))/sizeof(**(array)), array)
Then you can call the function and it will determine the dimensions itself:
FUNC_CALL_WITH_ARRAY(input_array);
Full example:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#define FUNC_CALL_WITH_ARRAY(array) func(sizeof(array)/sizeof(*(array)), sizeof(*(array))/sizeof(**(array)), array)
int func(int dim1, int dim2, float array[dim1][dim2])
{
printf("dim1 %d, dim2 %d\n", dim1, dim2);
return 0;
}
#define DIMENSION1 (4)
#define DIMENSION2 (512)
int main(int argc, char *argv[])
{
float input_array[DIMENSION1][DIMENSION2];
FUNC_CALL_WITH_ARRAY(input_array);
float input_array2[7][16];
FUNC_CALL_WITH_ARRAY(input_array2);
}
Will print
dim1 4, dim2 512
dim1 7, dim2 16
Dimensions vary depending on the use case, and the func should stay the same.
Use VLA:
void func (int r, int c, float arr[r][c]) {
//access it like this
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
printf ("%f\n", arr[i][j]);
}
}
}
// call it like this
func (DIMENSION1, DIMENSION2, input_array);
You can change your function like this;
int func(float (*arr)[DIMENSION2])
{
}
But also you should change your main code like this;
float input[DIMENSION1][DIMENSION2];//I just upload the dimension1 to dimension2
As noted above in the comment, the key problem is that int func(float *name[]) declares name to be an array of pointers to float.
In this sense, the following modification to main() works:
int main(int argc, char *argv[])
{
float input_array[DIMENSION1][DIMENSION2] =
{
{0.0f, 0.1f, 0.2f},
{1.0f, 1.1f, 1.2f}
};
/* Declare an array of pointers, as this is what func requires at input: */
float* in_p[DIMENSION1];
/* ... and initialize this array to point to first elements of input array: */
for( int i=0;i<DIMENSION1;i++)
in_p[i] = input_array[i];
/* ... and send this array of pointers to func: */
func(in_p);
return 0;
}
This is going to present a very old solution, one that works on every C compiler that exists. The idea goes something like this:
I have multiple pieces of information to keep track of
I should keep them together
This leads us to the idea that we can use a composite type to hold all the related information in one place and then treat that object as a single entity in our code.
There is one more pebble in our bowl of sand:
the size of the information varies
Whenever we have varying-sized objects, dynamic memory tends to get involved.
Arrays vs Pointers
C has a way of losing information when you pass an array around. For example, if you declare a function like:
void f( int a[] )
it means exactly the same thing as:
void f( int * a )
C does not care that the size of the array is lost. You now have a pointer. So what do we do? We pass the size of the array also:
void f( int * a, size_t n )
C99 says “I can make this prettier, and keep the array size information, not just decay to a pointer”. Okay then:
void f( size_t dim1, size_t dim2, float array[dim1][dim2] )
We can see that it is pretty, but we still have to pass around the array’s dimensions!
This is reasonable, as the compiler needs to make the function work for any array, and array size information is kept by the compiler, never by executable code.
The other answers here either ignore this point or (helpfully?) suggest you play around with macros — macros that only work on an array object, not a pointer.
This is not an inherently bad thing, but it is a tricky gotcha: you can hide the fact that you are still individually handling multiple pieces of information about a single object,
except now you have to remember whether or not that information is available in the current context.
I consider this more grievous than doing all the hard stuff once, in one spot.
Instead of trying to juggle all that, we will instead use dynamic memory (we are messing with dynamic-size arrays anyway, right?)
to create an object that we can pass around just like we would with any other array.
The old solution presented here is called “the C struct hack”. It is improved in C99 and called “the flexible array member”.
The C struct hack has always worked with all known compilers just fine, even though it is technically undefined behavior.
The UB problem comes in two parts:
writing past the end of any array is unchecked, and therefore dangerous, because the compiler cannot guarantee you aren’t doing something stupid outside of its control
potential memory alignment issues
Neither of these are an actual issue. The ‘hack’ has existed since the beginning (much to Richie’s reported chagrin, IIRC), and is now codified (and renamed) in C99.
How does this magic work, you ask?
Wrap it all up in a struct:
struct array2D
{
int rows, columns;
float values[]; // <-- this is the C99 "flexible array member"
};
typedef struct array2D array2D;
This struct is designed to be dynamically-allocated with the required size. The more memory we allocate, the larger the values member array is.
Let’s write a function to allocate and initialize it properly:
array2D * create2D( int rows, int columns )
{
array2D * result = calloc( sizeof(array2D) + sizeof(float) * rows * columns, 1 ); // The one and only hard part
if (result)
{
result->rows = rows;
result->columns = columns;
}
return result;
}
Now we can create a dynamic array object, one that knows its own size, to pass around:
array2D * myarray = create2D( 3, 4 );
printf( "my array has %d rows and %d columns.\n", myarray->rows, myarray->columns );
free( myarray ); // don’t forget to clean up when we’re done with it
The only thing left is the ability to access the array as if it were two-dimensional.
The following function returns a pointer to the desired element:
float * index2D( array2D * a, int row, int column )
{
return a->values + row * a->columns + column; // == &(a->values[row][column])
}
Using it is easy, if not quite as pretty as the standard array notation.
But we are messing with a compound object here, not a simple array, and it goes with the territory.
*index2D( myarray, 1, 3 ) = M_PI; // == myarray[ 1 ][ 3 ] = M_PI
If you find that intolerable, you can use the suggested variation:
float * getRow2D( array2D * a, int row )
{
return a->values + row * a->columns; // == a->values[row]
}
This will get you “a row”, which you can array-index with the usual syntax:
getRow2D( myarray, 1 )[ 3 ] = M_PI; // == myarray[ 1 ][ 3 ] = M_PI
You can use either if you wish to pass a row of your array to a function expecting only a 1D array of floats:
void some_function( float * xs, int n );
some_function( index2D( myarray, 1, 0 ), myarray->columns );
some_function( getRow2D( myarray, 1 ), myarray->columns );
At this point you have already seen how easy it is to pass our dynamic 2D array type around:
void make_identity_matrix( array2D * M )
{
for (int row = 0; row < M->rows; row += 1)
for (int col = 0; col < M->columns; col += 1)
{
if (row == col)
*index2D( M, row, col ) = 1.0;
else
*index2D( M, row, col ) = 0.0;
}
}
Shallow vs Deep
As with any array in C, passing it around really only passes a reference (via the pointer to the array, or in our case, via the pointer to the array2D struct).
Anything you do to the array in a function modifies the source array.
If you want a true “deep” copy of the array, and not just a reference to it, you still have to do it the hard way.
You can (and should) write a function to help.
This is no different than you would have to do with any other array in C, no matter how you declare or obtain it.
array2D * copy2D( array2D * source )
{
array2D * result = create2D( source->rows, source->columns );
if (result)
{
for (int row = 0; row < source->rows; row += 1)
for (int col = 0; col < source->cols; col += 1)
*index2D( result, row, col ) = *index2D( source, row, col );
}
return result;
}
Honestly, that nested for loop could be replaced with a memcpy(), but you would have to do the hard stuff again and calculate the array size:
array2D * copy2D( array2D * source )
{
array2D * result = create2D( source->rows, source->columns );
if (result)
{
memcpy( result->values, source->values, sizeof(float) * source->rows * source->columns );
}
return result;
}
And you would have to free() the deep copy, just as you would any other array2D that you create.
This works the same as any other dynamically-allocated resource, array or not, in C:
array2D * a = create2D( 3, 4 ); // 'a' is a NEW array
array2D * b = copy2D( a ); // 'b' is a NEW array (copied from 'a')
array2D * c = a; // 'c' is an alias for 'a', not a copy
...
free( b ); // done with 'b'
free( a ); // done with 'a', also known as 'c'
That c reference thing is exactly how pointer and array arguments to functions work in C, so this should not be something surprising or new.
void myfunc( array2D * a ) // 'a' is an alias, not a copy
Hopefully you can see how easy it is to handle complex objects like variable-size arrays that keep their own size in C, with only a minor amount of work in one or two spots to manage such an object. This idea is called encapsulation (though without the data hiding aspect), and is one of the fundamental concepts behind OOP (and C++). Just because we’re using C doesn’t mean we can’t apply some of these concepts!
Finally, if you find the VLAs used in other answers to be more palatable or, more importantly, more correct or useful for your problem, then use them instead! In the end, what matters is that you find a solution that works and that satisfies your requirements.

Warning: Return from incompatible pointer type

The code below is producing a compiler warning: return from incompatible pointer type. The type I'm returning seems to be the issue but I cant seem to fix this warning.
I have tried changing the type of hands to int *. Also have tried returning &hands.
int * dealDeck(int numPlayers, int numCards, int cardDeck[])
{
static int hands[MAX_PLAYERS][MAX_CARDS]={0};
int start = 0;
int end = numCards;
int player, hand, j;
int card;
for(player = 0; player < numPlayers; player++)
{
for(hand = start, j=0; hand < end; hand++,j++)
{
card = cardDeck[hand];
hands[player][j] = card;
}
start = end;
end += numCards;
}
return hands;
}
This function should return a pointer to the array "hands". This array is then passed to another function which will print out its elements.
The hands variable is not an int * this is a int **
So you need to return a int **
This is a 2d array.
First of all, you have declared return type of int *, which would mean, that you are trying to return an array, while you want to return a 2-dimensional array. The proper type for this would usually be int **, but that won't cut it here. You opted to go with static, fixed size array. That means, that you need to return pointer to some structures of size MAX_CARDS * sizeof(int) (and proper type, which is the real problem here). AFAIK, there is no way to specify that return type in C*.
There are many alternatives though. You could keep the static approach, if you specify only up to 1 size (static int *hands[MAX_PLAYERS] or static int **hands), but then you need to dynamically allocate the inner arrays.
The sane way to do it is usually "call by reference", where you define the array normally before calling the function and you pass it as a parameter to the function. The function then directly modifies the outside variables. While it will help massively, with the maintainability of your code, I was surprised to find out, that it doesn't get rid of the warning. That means, that the best solution is probably to dynamically allocate the array, before calling the function and then pass it as an argument to the function, so it can access it. This also solves the question of whether the array needs to be initialized, and whether = {0} is well readable way to do it (for multidimensional array) , since you'll have to initialize it "manually".
Example:
#include <stdio.h>
#include <stdlib.h>
#define PLAYERS 10
#define DECKS 20
void foo(int **bar)
{
bar[0][0] = 777;
printf("%d", bar[0][0]);
/*
* no point in returning the array you were already given
* but for the purposes of curiosity you could change the type from
* void to int ** and "return bar;"
*/
}
int main()
{
int **arr;
arr = malloc(sizeof(int *) * PLAYERS);
for (size_t d = 0; d < DECKS; d++) {
/* calloc() here if you need the zero initialization */
arr[d] = malloc(sizeof(int) * DECKS);
}
foo(arr);
return 0;
}
*some compilers call such type like int (*)[20], but that isn't valid C syntax

Can't modify a 2D array of an unknown size within a fucntion in C

I new to C, and I just can't figure out how to modify a 2D array in a function.
Here's the code I tried:
void init_matrix(int **M) {
M[0][0] = 1;
}
int main(void) {
int M[3][3];
init_matrix(M, 3);
return 0;
}
(Please note that this code is voluntarily stripped down in order to focus on the issue, I need my function to be able to work on arrays of a globally unknown size (though it could be a parameter of the function))
When I try to run this, it just gets stuck... The debugger says it's a problem of right to write in this memory slot.
How would you write the init_matrix function in the C spirit ?
Why can't I write in my matrix ?
I would like to use as few "advanced" concepts and function as possible.
Thanks in advance =)
An array is not a pointer. You need to give the dimensions of the array when you pass it as a function parameter.
void init_matrix(size_t x, size_t y, int matrix[x][y])
{
for (size_t i = 0 ; i < x ; ++i)
{
for (size_t j = 0 ; j < y ; ++j)
matrix[i][j] = 1;
}
}
int main(void)
{
int matrix[5][3];
init_matrix(5, 3, matrix);
return (0);
}
The function init_matrix() takes as parameters the dimensions, then the array (this order is important here). The "double loop" is a classic for running through a "2D memory area" like our array.
(Note that you can forget the first dimension,
void init_matrix(size_t x, size_t y, int matrix[][y])
also works)

Container to save function pointer

I need a container to save function pointers to certain numbers.
Like
1 = function add
2 = function sub
3 = function mult
And so on. This is for a simple interrupt handler, where depending on the interrupt number a certain function should be called.
I thought that I can do this with a structured list, but I know the size of the maximal amount of entries. So I thought about an array of strings like
const char *functions[2];
a[0] = "add";
a[1] = "sub";
But then I don't know how I can further use the strings.
Any tips or thoughts?
Thanks in advance!
EDIT: To clarify, I have 2 important functions here, one, where I want to save a function pointer together with a number into some container. And another one, which just says "goto the function which is at a certain number in that container". So the first function gets an int number (say from 1 to 50) and a pointer to a function. Those should be saved together. The second function then just gets an int number as parameter and then it should call the function which is associated with that int number in my container. What I'm asking is how I could save a pointer that points to a function together with a number.
EDIT2: I do want to save function pointers. I thought I could maybe save the function name as a string and then use it later as function name because I didn't know another way.
If you want to store and use a function pointer you can do it like this:
// the functions you want to point to
int add(int a, int b) { do stuff }
int sub(int a, int b) { do some other stuff }
...
// declare and set a function pointer
int (*myFuncPtr) (int, int);
myFuncPtr = ⊂ // points to the function "sub". The & is optional
// now use it:
int result = myFuncPtr(23, 42);
The type of a function pointer depends on the return value and the parameters of the function you want to point to.
You can make the declaration of a function pointer variable easier
by using typedef:
typedef int (*funcPtr) (int, int);
Now declare and initialize a function pointer using the typedef like this:
funcPtr myFuncPtr = &add;
Of course you can now put many of those pointers into an array
and access them by the indices:
funcPtr funcPtrs[] = { &sub, add }; // like i said, the ampersand is optional
int result = funcPtrs[0](23, 42);
You have to store function pointers, so define a new function pointer type and make an array. According to your question the all functions should take two int parameters and return and int, so the new type should be something like this:
typedef int (*operation_t)(int,int);
Now you can create an array of operation_t. The whole code:
#include <stdio.h>
typedef int (*operation_t)(int,int);
int addInt(int n, int m) {
return n+m;
}
int subInt(int n, int m) {
return n-m;
}
int multipleInt(int n, int m) {
return n*m;
}
int main ()
{
const operation_t function_list[3] = {&addInt, &subInt, &multipleInt};
int i;
for(i = 0; i < 3; i++)
{
printf("inputs: 2 and 3 result: %d\n", function_list[i](2,3));
}
return 0;
}
The output:
Note that, as it's an array the indexes are 0, 1, 2.
To add an own ID you can create a stuct with the function pointer and an int ID.
typedef struct operation
{
int (*operation_p)(int,int);
int id;
} math_operation_t;
You can even build a linked list, and add functions dynamically if you define a third member variable, which should be the pointer to the next element.

golang return object from a function

I am struggling to understand exactly what is happening when you return a new object from a function in go.
I have this
func createPointerToInt() *int {
i := new(int)
fmt.Println(&i);
return i;
}
func main() {
i := createPointerToInt();
fmt.Println(&i);
}
The values printed returned are
0x1040a128
0x1040a120
I would expect these two values to be the same. I do not understand why there is an 8 byte difference.
In what I see as the equivalent C code:
int* createPointerToInt() {
int* i = new int;
printf("%#08x\n", i);
return i;
}
int main() {
int* r = createPointerToInt();
printf("%#08x\n", r);
return 0;
}
The address returned is the same:
0x8218008
0x8218008
Am I missing something blindingly obvious here? Any clarification would be greatly appreciated!
You are printing the address of the pointer here fmt.Println(&i);. Try this:
func main() {
i := createPointerToInt();
fmt.Println(i); //--> Remove the ampersand
}
i is the pointer returned from createPointerToInt - while &i is the address of the pointer you are trying to print. Note in your C sample you are printing it correctly:
printf("%#08x\n", r);
^No ampersand here
Change &i to i. You are printing address of i while you should print the value of i.
func createPointerToInt() *int {
i := new(int)
fmt.Println(i);
return i;
}
func main() {
i := createPointerToInt();
fmt.Println(i);
}
But how come in your original code the addresses of the two pointers (not memory addresses the pointers are pointing too) are different?
func main() {
i := createPointerToInt();
fmt.Println(&i);
}
Is equivalent to:
func main() {
var i *int // declare variable i
i = createPointerToInt(); // assign value of
// a different i that was
// declared and initialized
// inside the function
fmt.Println(&i);
}
Edit:
To print the address of a struct you need to use:
fmt.Printf("%p\n", &your_struct)
golang.org/pkg/fmt/
For example:
goplayground

Resources