-1

I need to load a library dynamically at runtime, and the code doesn't have the custom types the library uses defined at compile time.

This seems to initialize the struct correctly:

void *data = malloc(128);
InitCustomType(data);

The problem with this approach is that the size of the struct is unknown.

This is an example of how the library is normally used: (CustomType is a struct)

CustomType customType;
InitCustomType(&customType);

// Now customType can be used in the library calls
Lurkki
  • 17
  • 2
  • How about this? `CustomType* customType = (CustomType*) malloc(sizeof(CustomType)); InitCustomType(customType);` – kiner_shah Sep 06 '19 at 15:08
  • Could you modify the library to create a function that allocates the struct and returns a pointer to it? That way, the size will be good. – Olivier Darrouzet Sep 06 '19 at 15:13
  • Modifying the library isn't feasible in this case. – Lurkki Sep 06 '19 at 15:18
  • Surely the library or header would provide some s.atic or dynamic means to determine the size? Either a macro, or a function call, or a documented value. – Ian Abbott Sep 06 '19 at 16:40
  • 1
    The C program really needs to know the types in use before it can use them — unless the library is set up to allow use as opaque types (accessed via pointers). You're on a rocky road. You might be able to use the external interface to the code in the library as documented by headers to create access functions which you could load in parallel with the dynamic library, but that isn't easy. You can't simply use any old shared library in a program; you have to know enough about how to use it, what the rules for access are, to be able to do the job properly. – Jonathan Leffler Sep 06 '19 at 16:55

1 Answers1

1

This is an example of how the library is normally used: (CustomType is a struct)

If that is an example, then nothing should stop you from using CustomType, or using malloc(sizeof(CustomType)).

the code doesn't have the custom types the library uses defined at compile time.

That statement is inconsistent with above. Either you do have a definition of CustomType, or you don't. If you do, you don't have a problem. If you don't, you can't really use this library.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362