andrei-markeev / ts2c

Convert Javascript/TypeScript to C
ISC License
1.26k stars 95 forks source link

C functions #77

Closed cybe42 closed 3 years ago

cybe42 commented 3 years ago

hello, are there any way I can call c functions without getting something like this: /* Unsupported function call: printf("a") */;

neimanpinchas commented 3 years ago

yes, I would also advocate for such a feature.

we must have a way to include raw c in the source files

Until we implement a new runtime, we should be able to use the underlying runtime

andrei-markeev commented 3 years ago

This is already possible, you need to create a "runtime" project with header definitions similar to https://github.com/andrei-markeev/ts2c-target-esp-idf or https://github.com/andrei-markeev/ts2c-target-gbdk-n.

So first, you create a TS definition like this:

declare module "ts2c-target-c89/stdio.h" {
    function printf(template: string, ...args: any[]): number;
}

Naming is important, it should start with "ts2c-target-". Put this module so that it can be found by TS (which is, in most cases, means putting it to node_modules).

After this, you should be able to do

import { printf } from 'ts2c-target-c89/stdio.h';

printf("a");

Working example is available in tests/statements/import_target.ts - which depends on types from tests/statements/node_modules/ts2c-target-test/stdlib.h.d.ts, and generates the following output file: tests/statements/import_target.c.

Some more information that might be useful: https://github.com/andrei-markeev/ts2c-target-esp-idf/issues/1#issuecomment-741875644