vico
vico

Reputation: 18191

Create API function that returns array of structures

I'm trying to create library in C++ that will be used by various programming languages (like Java, C++, C#). Code will be cross platform (Linux/Windows). One function should return array of simple structures:

struct Aaa {
    int c;
    int d;
}

What is the best way to pass array of Aaa to caller?

I was thinking about function signature that helps to get [] of Aaa to caller, but it's realization is complicated.

void abc(Aaa* a[], *int array_length ) 
{
...
}

One of alternatives is to return std::vector, but I suppose Java and C# will be not happy about that?

Upvotes: 1

Views: 124

Answers (1)

eerorika
eerorika

Reputation: 238401

that will be used by various programming languages (like Java, C++, C#)

In that case, you need an API in the C language. You can create a wrapper for each language to make the C API more convenient, but the shared code has to be behind C API. The API functions can themselves be defined in C++.

Create API function that returns array of structures

You cannot return arrays in C. One approach would be to dynamically allocate an array, but that is sometimes not desirable.

Creation of an array typically consists of two sub-taks: Allocation of an array, and initializing the elements of the array. Often, it is a good idea to design a C API such that the library itself doesn't allocate arrays. The arrays can be allocated by the caller. This is particularly convenient in cross language libraries where some languages have vastly different strategies for memory allocation.

In C, you pass arrays using a pointer to the first element of the array. If the length varies, you also send that. Like so:

void abc(Aaa array[], size_t size)
// alternative spelling that is semantically equivalent:
void abc(Aaa* array, size_t size)

Upvotes: 2

Related Questions