필터 지우기
필터 지우기

How to call object methods with c++ engine api?

조회 수: 12 (최근 30일)
Kyösti Alkio
Kyösti Alkio 2022년 9월 6일
편집: Ramtej 2023년 9월 6일
I'm using C++ Engine Api to call MATLAB code from C++. I want to create an instance of a MATLAB class from C++ and call its methods. How can I achieve this?
Currently, I'm using this kind of approach to create the instance (Processor is the name of class I'm trying to use):
matlab = matlab::engine::startMATLAB();
matlab->eval(u"addpath 'path/to/folder/with/class.m'");
matlab->eval(u"processor = Processor");
After that, I'm not sure what to do. I tried using
matlab->feval<int>(u"processor.add_simple");
but I only get error Unrecognized function or variable 'processor.add_simple'.
There seems also to be matlab->getProperty and matlab->setProperty methods, but I want to get methods instead of properties.
Furthermore, the whole approach of using eval to create the instance seems pretty cumbersome. Is there a way to instantiate the class directly from c++, perhaps something like this:
auto instance = matlab->create_instance("class_name")
instance->call_method("method_name", args)
or
matlab->call_instance_method(instance, "method_name", args)
What is the correct way of using C++ Engine Api with class instances?

답변 (1개)

Ramtej
Ramtej 2023년 9월 6일
편집: Ramtej 2023년 9월 6일
Hi Kyösi,
I understand that you are trying to call object methods with c++ engine api.
The error " Unrecognized function or variable 'processor.add_simple' " occurred because "feval" assumes "processor.add_simple" as the name of the function you are trying to call.
To call object methods follow the steps below:
%create an object handle for your class object
matlab::data::Array objHandle = matlabPtr->getVariable(u"processor"); % 'processor' in your case
% pass this object handle as an input to the object method you are trying
% to call. You are invoking the object method by evaluating "processor(add_simple)" which is
% equivalent to "processor.add_simple"
matlab::data::Array results = matlabPtr->feval(u"add_simple", objHandle);
If your object method ("add_simple") accepts any input variables other than object ("processor") itself which should be passed by default, refer to "feval" documentation for detailed instructions on how to evaluate MATLAB functions with input arguments.
Hope this resolves you query!

카테고리

Help CenterFile Exchange에서 Data Exchange and Mapping with C++ Applications에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by