Вопрос

I am trying to create a macro (C/C++) to dynamically create a function. Basically I have a function whose name varies in the "MyClassA" part. Also the arguements should be passed through the macro definition. Then there is a variable method call within the function, for instance "methodForClassA", again with a variable set of arguements.

void Java_somepackage_MyClassA_fixMethod(int arg1, int arg2) {
Toolbox.methodForClassA(arg1, arg2);
}

There are more than 40 functions with this pattern. Of course I can create them manually or with a script. But is it also possible to do this with a macro? For instance something like this (which does not work):

# define MACRO_TEST(classname, methodname, args, argsMethod) void Java_somepackage_##classname_fixMethod(##args) {\
    Toolbox.##methodname(##argsMethod);\
} 
MACRO_TEST(MyClassA, methodForClassA, args1, args2)

After some experimentation and reading of docs, I could only find out how to create "dynamic" function names with patterns where a "(" follows the dynamic part:

#define FUNCTION(name, x) int func_##name() { return x;}
FUNCTION(test, 2);

Regards,

Это было полезно?

Решение

I think you may be misunderstanding the purpose of the ## symbol pasting operator. You don't need to put ## in front of every use of a macro argument, only when you want to paste it together with some other text to create one symbol in the output. So, you will probably need it, but not everywhere.

So this is closer:

# define MACRO_TEST(classname, methodname, args, argsMethod) \
void Java_somepackage_##classname##_fixMethod(args) {\
    Toolbox.methodname(argsMethod);\
} 
MACRO_TEST(MyClassA, methodForClassA, args1, args2)

However, this still doesn't work. Your args parameter I guess contains a variable number of parameters. In newer versions of C, there's something called "variadic macro parameters" but I've never used them. Or, you could surround your parameters with parentheses in the macro call, like this:

# define MACRO_TEST(classname, methodname, args, argsMethod) \
void Java_somepackage_##classname##_fixMethod args  {\
    Toolbox.methodname argsMethod;\
} 
MACRO_TEST(MyClassA, methodForClassA, (int arg1, int arg2), (arg1, arg2))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top