1

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?

2
  • 4
    Generally I would use STL containers internally in C++ then convert at the API boundaries to whatever the other consuming languages need. Commented Jan 26, 2018 at 12:52
  • 1
    Return a std::vector, then wrap it up so other types can be provided for languages that need them. Commented Jan 26, 2018 at 12:57

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.