Skip to content

Instantly share code, notes, and snippets.

@NSExceptional
Created November 3, 2022 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NSExceptional/7e13a8a49ade703b16438940c1260b1b to your computer and use it in GitHub Desktop.
Save NSExceptional/7e13a8a49ade703b16438940c1260b1b to your computer and use it in GitHub Desktop.
Lookup and invoke a CPP function at runtime
#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