Home > Software engineering >  How to compile typescript code along with C ?
How to compile typescript code along with C ?

Time:11-30

I have a project which is completely in C . Also I have one more file which is in typescript ( I wasn't able to find libraries equilvelent in C ). The typescript file is doing the following: 1 It has typescript CLI code kinda of generator that will generate some functions in respective files.

My compiler is gcc.

Can please someone tell me .. is it possible to link and compile it ? Is yes..How ?

typescriptfile.ts

   #!/usr/bin/env node

import * as fs from "fs"
import * as path from "path"
import { Project } from "ts-morph"
import { generateerr } from "./errors"
import { generateProgId } from "./programId"
import { program } from "commander"


async function main() {
  program
    .description(
  )
    .argument()
    .argument()
    .option()
    .version()
    .parse()

  const idlPath = program.args[0]
  const outBase = program.args[1]
  const programIdOpt: string | null = program.opts().programId || null

  function outPath(filePath: string) {
    return path.join(outBase, filePath)
  }

  const idl = JSON.parse(fs.readFileSync(idlPath).toString())

  const project = new Project()

  console.log("generating programId")
  generateProgId(project, idl, programIdOpt, outPath)
  console.log("generating errors.ts")
  generateerr(project, idl, outPath)
  

  const files = project.getSourceFiles()

  console.log("formatting...")
  await Promise.all(
    files.map(async (file) => {
      let src = file.getFullText()
      file.replaceWithText(src)
    })
  )

  console.log("writing files...")
  await project.save()
}

main().catch((e) => {
  console.error(e.message)
  process.exit(1)
})

CodePudding user response:

tl;dr provide a node executable and use spawn a node myfile.js from your program


  1. You (generally) can't compile typescript into bytecode, it will always be a .JS text file executed with #!/usr/bin/env node

  2. If you want to run JS from C , the easiest way is to exec or spawn node process

  3. If you want to run C from JS, the easiest way is to exec or spawn c process, but if you want to dig into that look for how to make bindings for node https://nodejs.org/api/addons.html

CodePudding user response:

A relatively easy way to bridge C and JS/TS is node-addon-api. There's a simplified API for this, inline-cpp, which I have a branch for:

Example JS (same with TS):

const hello = InlineCPP `
  String func(const CallbackInfo& info) {
    return String::New(info.Env(), "Hello world!");
  }
`
console.log(hello()); // Hello world!
  • Related