함수이름을 입력으로 함수를 실행할 수 있는 방법이 있을까요?

whacker의 이미지

갑자기 코딩중 궁금증이 생겼습니다.

만약 어떠한 인풋값(ex) a.txt 라는 파일에 hello 라는 문자열이 있습니다.) 을 통해서

그 문자열과 동일한 이름의 함수나 변수를 인식할 수 있을까요?

hello라는 문자열을 입력받으면 hello라는 함수를 실행시키도록 말이죠.

if문으로 비교해서 직접 실행시키는 방법말고

해당 문자열 값으로 변수나 함수이름을 접근할 수 있는 방법이 있는지 궁금합니다. ㅜㅜ

나그네나그네의 이미지

reflection와 meta class란 키워드로 찾아보시면 될 듯 합니다.

C라면 dynamic linking을 소스코드에서 구현할 수 있는 표준 라이브러리가 잇는데, 그 과정에서 함수 이름을 인자로 전달하는데 이를 사용하면 될 듯 합니다.
예 : (본인이 만든) libvector.so 라이브러리에서 특정 함수 호출하기 :
(dlfcn.h를 include한 뒤)
void *handle = dlopen("./libvector.so", RTLD_LAZY);
void (*addvec)(int *, int *, int *, int); // 부르고자 하는 함수의 포인터
addvec = dlsym(handle, "addvec"); // addvec이란 함수 포인터를 가져옴
addvec(x, y, z, 2);

JAVA라면 reflection이 아주 훌륭하게 구현되어 있습니다. java.lang.reflect 패키지와 Class.getDeclaredField(String), Class.getDeclaredMethod(String, ...)을 참조하시면 될 듯 합니다.

whacker의 이미지

C에서 혹시 라이브러리가 아니라면 불가능한가요?
일반 바이너리라거나 main이 포함된 코드의 경우에는 방법이 없는지요?
친절한 답변 감사합니다.

wariua의 이미지

dlopen()의 첫 번째 인자를 NULL로 주면 프로그램 자체에서 심볼을 찾습니다. (좀 더 정확한 내용은 manpage 설명을 참고하세요~)

단, 그 프로그램 역시 -rdynamic 컴파일러 옵션을 줘서 컴파일 해야 합니다.

$PWD `date`

M.W.Park의 이미지

functional programming language??

-----
오늘 의 취미는 끝없는, 끝없는 인내다. 1973 法頂

익명 사용자의 이미지

typedef void (*slot)();
 
void hello() {}
void world() {}
 
// initialize function table
map<string, slot> funtab;
funtab["hello"] = hello;
funtab["world"] = world;
...
 
// read input
while (cin >> name) {
    funtab[name]();
}

익명 사용자의 이미지

가능해도 사실 큰 의미는 없는 것이
보안상 사용 가능한 함수 목록은 white list 형식으로
허용되는 함수들 안에서 선택 가능해야 하는데
그렇게 되면 그냥 함수 이름 문자열과 함수 포인터를 가진 테이블을 만들어서
하는 거랑 크게 다를바가 없기 때문이죠.

snowall의 이미지

느낌상, 링커나 로더 수준에서 접근해야할 것 같은데요.

함수의 심볼을 처리해야 할 테니...

C언어만 갖고서는 잘 안될 것 같네요.

피할 수 있을때 즐겨라! http://melotopia.net/b

cinsk의 이미지

원칙적으로는 불가능하지만, dyncall이라는 library가 있습니다. 지원가능한 컴파일러/OS가 좀 제한적이긴 하지만. :)

http://dyncall.org/

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.