cxx icon indicating copy to clipboard operation
cxx copied to clipboard

How to pass stack allocated data back to Rust

Open xrl opened this issue 3 years ago • 0 comments

I want to access a C++ from Rust, the library is called RDKit. I need to call the TautomerEnumerator method "enumerate": https://www.rdkit.org/docs/cppapi/classRDKit_1_1MolStandardize_1_1TautomerEnumerator.html#a9d6498bda978cf437f3b665a271fe5e7

My wrapper code looks like:

#include "rust/cxx.h"
#include "GraphMol/GraphMol.h"
#include "GraphMol/SmilesParse/SmilesParse.h"
#include "GraphMol/SmilesParse/SmilesWrite.h"
#include "DataStructs/ExplicitBitVect.h"
#include "GraphMol/Fingerprints/Fingerprints.h"
#include "GraphMol/MolStandardize/Tautomer.h"

namespace RDKit {
    using TautomerEnumerator = MolStandardize::TautomerEnumerator;
    using TautomerEnumeratorResult = MolStandardize::TautomerEnumeratorResult;

    TautomerEnumerator *tautomer_enumerator() {
        return new MolStandardize::TautomerEnumerator(new MolStandardize::TautomerCatalog());
    }

    TautomerEnumeratorResult *enumerate_tautomer(TautomerEnumerator *enumerator, std::shared_ptr<ROMol> mol) {
        return enumerator->enumerate(*mol);
    }
}

but the problems is that enumerator->enumerate() returns a stack allocated variable which fails with:

  cargo:warning=wrapper/src/rdmol.cc:48:16: error: no viable conversion from returned value of type 'RDKit::MolStandardize::TautomerEnumeratorResult' to function return type 'RDKit::TautomerEnumeratorResult *' (aka 'RDKit::MolStandardize::TautomerEnumeratorResult *')
  cargo:warning=        return enumerator->enumerate(*mol);
  cargo:warning=               ^~~~~~~~~~~~~~~~~~~~~~~~~~~

what's a good way to move the stack allocated enumerator instance to the heap? or perhaps I should make the TautomerEnumeratorResult in to a non-opaque type so I can just pass it around at-will? How do I make a C++ class (not struct) transferrable from C++ to Rust?

xrl avatar Apr 29 '22 19:04 xrl