Created
November 3, 2022 23:07
-
-
Save NSExceptional/7e13a8a49ade703b16438940c1260b1b to your computer and use it in GitHub Desktop.
Lookup and invoke a CPP function at runtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#include <string> | |
#include <dlfcn.h> | |
class Foo { | |
int bar = 0; | |
std::string toString(); | |
}; | |
std::string Foo::toString() { | |
this->bar++; | |
return "hello " + std::to_string(this->bar); | |
} | |
typedef std::string (*ReturnsString)(void *); | |
int main(int argc, const char * argv[]) { | |
std::string (*toStringMethod)(void *) = (ReturnsString)dlsym(RTLD_DEFAULT, "_ZN3Foo8toStringEv"); | |
if (!toStringMethod) return 0; | |
auto foo = Foo(); | |
void *fooptr = &foo; | |
auto hellostr = toStringMethod(fooptr); | |
if ([@"hello 1" isEqualToString:@(hellostr.c_str())]) { | |
NSLog(@"yay"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment