Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 636633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T20:32:11+00:00 2026-05-13T20:32:11+00:00

In order to define a method in C that is callable by Lua it

  • 0

In order to define a method in C that is callable by Lua it has to match a given signature and use the Lua API to retrieve parameters and return results. I’m writing a C# wrapper of Lua and I’m interested in being able to call arbitrary C# methods without making them follow these conventions. When wrapping in something like D, one might use the template system to dynamically create this glue code for any given method. I was thinking this might be possible as well in C#, but by using dynamic code generation.

The C API looks something like this, and the generated code would manipulate this through a lower level part of my library which P/Invokes the Lua C library.

static int foo (lua_State *L)
{
    int n = lua_gettop(L);    /* number of arguments */
    lua_Number sum = 0;
    int i;
    for (i = 1; i <= n; i++)
    {
        if (!lua_isnumber(L, i)) 
        {
            lua_pushstring(L, "incorrect argument");
            lua_error(L);
        }
        sum += lua_tonumber(L, i);
    }
    lua_pushnumber(L, sum/n);        /* first result */
    lua_pushnumber(L, sum);         /* second result */
    return 2;                   /* number of results */
}

So basically the idea is to take a C# method, reflect its parameters and return values, generate (or retrieve from cache) a method that uses the Lua API like above to pass those parameters and return those return types and finally push that method to Lua. So when C# function is called from Lua it looks something like lua -> magic wrapper function -> ordinary C# function.

Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T20:32:12+00:00Added an answer on May 13, 2026 at 8:32 pm

    If I understand what you want, it seems you have 2 options:

    1. use the CodeDOM to generate and dynamically compile code, at runtime.
    2. emit actual C# source code, and dynamically compile it into a callable assembly at runtime.

    CodeDom is sort of hairy, very low-level code to write. The idea is there’s an object model for the C# language. You start by instantiating a CodeTypeDeclaration – this will generate a type or class. Then you add properties and fields – here you would likely add DllImport declarations for your p/invoke functions. Then you use different CodeDOM add methods to the type – this would be where you’d insert the generated method. You could make it public, static, whatever you like.

    CodeDOM looks like this:

    System.Type mt= a[0].GetType();
    
    System.CodeDom.CodeTypeDeclaration class1 = new System.CodeDom.CodeTypeDeclaration(mt.Name);
    class1.IsClass=true;
    class1.TypeAttributes = System.Reflection.TypeAttributes.Public;
    class1.Comments.Add(new System.CodeDom.CodeCommentStatement("Wrapper class for " + mt.Name));
    
    System.CodeDom.CodeConstructor ctor;
    ctor= new System.CodeDom.CodeConstructor();
    ctor.Attributes = System.CodeDom.MemberAttributes.Public;
    ctor.Comments.Add(new System.CodeDom.CodeCommentStatement("the null constructor"));
    class1.Members.Add(ctor);
    ctor.Statements.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeVariableReferenceExpression("m_wrapped"), new System.CodeDom.CodeObjectCreateExpression(mt)));
    
    ctor= new System.CodeDom.CodeConstructor();
    ctor.Attributes = System.CodeDom.MemberAttributes.Public;
    ctor.Comments.Add(new System.CodeDom.CodeCommentStatement("the 'copy' constructor"));
    class1.Members.Add(ctor);
    ctor.Parameters.Add(new System.CodeDom.CodeParameterDeclarationExpression(mt,"X"));
    ctor.Statements.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeVariableReferenceExpression("m_wrapped"), new System.CodeDom.CodeVariableReferenceExpression("X")));
    
    // embed a local (private) copy of the wrapped type
    System.CodeDom.CodeMemberField field1;
    field1= new System.CodeDom.CodeMemberField();
    field1.Attributes = System.CodeDom.MemberAttributes.Private;
    field1.Name= "m_wrapped";
    field1.Type=new System.CodeDom.CodeTypeReference(mt);
    class1.Members.Add(field1);
    
    ...
    

    it goes on. and on. As you can see, it gets pretty ugly. Then later you compile it, which I did not show. I’m assuming you’re not gonna want to take this approach.


    I found CodeDom to be pretty crufty to use; instead, now when I need dynamically-generated assemblies, I will emit actual C# code, normally via templates, into a string in memory, and compile that. It’s much simpler for my purposes. The compilation looks like this:

    var cp = new System.CodeDom.Compiler.CompilerParameters {
      ReferencedAssemblies.Add(filesystemLocation), // like /R: option on csc.exe
      GenerateInMemory = true,    // you will get a System.Reflection.Assembly back
      GenerateExecutable = false, // Dll
      IncludeDebugInformation = false,
      CompilerOptions = ""
    };
    
    var csharp = new Microsoft.CSharp.CSharpCodeProvider();
    
    // this actually runs csc.exe:
    System.CodeDom.Compiler.CompilerResults cr = 
          csharp.CompileAssemblyFromSource(cp, LiteralSource);
    
    
    // cr.Output contains the output from the command
    
    if (cr.Errors.Count != 0)
    {
        // handle errors
    }
    
    System.Reflection.Assembly a = cr.CompiledAssembly;
    
    // party on the type here, either via reflection...
    System.Type t = a.GetType("TheDynamicallyGeneratedType");
    
    // or via a wellknown interface
    

    In the above code, LiteralSource contains the source code to be compiled. As I said, I generate this by reading a template and filling in the blanks.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 487k
  • Answers 487k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer It sounds like what you have is a Software Product… May 16, 2026 at 8:17 am
  • Editorial Team
    Editorial Team added an answer Sonar : http://www.sonarsource.org/ ? May 16, 2026 at 8:17 am
  • Editorial Team
    Editorial Team added an answer The syntax presented in your question is correct, here is… May 16, 2026 at 8:17 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.