SlideShare a Scribd company logo
Dmitri Nesteruk
JetBrains
Managed language = C#, Java, D etc.
GC (garbage collector), Unicode, …
Unmanaged language
Something that compiles to native code
More control, less safety
C/C++, VHDL, etc.
Performance
Stop-the-world GC
Low-level control (e.g., SIMD)
Collections (containers), multithreading
Defense against reverse-engineering
C#, Java are easy to decompile
Hardware support
CUDA, Xeon Phi
Portability (surprise!)
Sudden desire to write everything in С++
Lex the source code
Build AST
Resolve symbols
Traverse the tree, translating it to a different
language
Perfect translation is (of course) impossible
Translate syntax with fidelity
Fill the gaps in what’s missing
Replace equivalent constructs
List<>  vector<>
Handle cases where 1-to-1
mapping is impossible
Integral types
Use types from <cstdint>
int int32_t, byte  uint8_t, etc.
float/double as-is
Extended precision types (System.Decimal)
Need external libs 
Slightly different init rules
Unicode 
Most LoB apps do not absolutely require Unicode (nice to
have)
Relatively safe option:
string  std::wstring
char  wchar_t
Slightly more careless option: string/char
A completely safe solution has to allow strings to be nullptr
I.e., you either use char* or option<string>
Expensive, tedious, just use myString.empty()
Unicode in source (identifiers, literals, …) won’t work
class Person
{
string name;
int age;
}
class Person {
std::string name;
int32_t age;
public:
Person();
};
Managed languages
Give types default values
Allow initialization right in the declaration
In both cases, initialization happens in the
(generated) ctor
In C++, types don’t have default values. So we
are forced to make a constructor ourselves
Property = field+getter+setter
Can be read or write-only
Can be automatic
Name of field not specified
explicitly
Offers no benefit over a field in C++
Can have an inline initializer
More ctor abuse 
Two options here
GetXxx/SetXxx (safe, tedious)
__declspec(property)
(not C++ standard, but nicer)
int age;
public int Age
{
get { return age; }
set { age = value; }
}
// automatic
public int Age
{ get; set; }
__declspec(property(get = GetAge, put = PutAge))
int Age;
int GetAge() const { return age; }
void PutAge(int value) { … }
// later
Person p;
p.Age = 123; // calls PutAge()
Used in many places, e.g.:
Handling UI interactions
Property change notifications
C++ doesn’t have them
Boost.Signals
Tricky since event subscription is done with +=
And unsubscription with −=
template <typename T> class
INotifyPropertyChanged
{
public:
signal<void(const T*, string)>
PropertyChanged;
};
class Player : public INotifyPropertyChanged<Player>
{
int age;
public:
__declspec(property(get = GetAge, put = PutAge)) int Age;
int GetAge() const { return age; }
void PutAge(int value)
{
if (value == age) return;
PropertyChanged(this, "Age"); // oops, a string! (macro?)
age = value;
}
“The big problem”
GC  non-GC translation
Store everything as shared_ptr
Replace every `new` with make_shared
Detecting use-cases for make_unique very
difficult
Circular references (weak_ptr<>?)
References require#includes
Need a list of typeheader for STL etc.
Circular references may need forward
declarations
Header groupings (at namespace or folder
level)
Very tricky internal consistency (topological sort)
Also a good idea for IDEs
Type translation is (relatively) easy
int  int32_t
List<T>  vector<T>
Function call translation is harder
List.Add()  vector.emplace_back(), but…
Value vs ref. stuff
We need two converters
One for .H files
Another for .CPP files (implementation)
The option of doing everything inline isn’t
considered
There are situations where 100% inlining doesn’t
work
Конверсия управляемых языков в неуправляемые
Naming convention
Clean Unicode handling
Automated API mapping
Questions?
dn@jetbrains.com
@dnesteruk
Come to the JB booth! (R#C++, CLion)

More Related Content

PDF
Address/Thread/Memory Sanitizer
PDF
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
PDF
C++ How I learned to stop worrying and love metaprogramming
PPTX
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
PDF
DLL Design with Building Blocks
PPTX
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
PDF
2018 cosup-delete unused python code safely - english
PPTX
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Address/Thread/Memory Sanitizer
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
C++ How I learned to stop worrying and love metaprogramming
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
DLL Design with Building Blocks
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
2018 cosup-delete unused python code safely - english
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson

What's hot (20)

PPTX
Best Bugs from Games: Fellow Programmers' Mistakes
PDF
Q4.11: Using GCC Auto-Vectorizer
PDF
Basic c++ 11/14 for python programmers
PDF
Fun with Lambdas: C++14 Style (part 1)
PPTX
How to add an optimization for C# to RyuJIT
PDF
GPU Programming on CPU - Using C++AMP
PDF
HKG15-207: Advanced Toolchain Usage Part 3
PPTX
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
PDF
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
PPTX
Fun with Lambdas: C++14 Style (part 2)
PDF
Arduino C maXbox web of things slide show
PPTX
Summary of C++17 features
PPTX
C++ 11 Features
PDF
To Swift 2...and Beyond!
PDF
Autovectorization in llvm
PDF
Bartosz Milewski, “Re-discovering Monads in C++”
PDF
Q4.11: NEON Intrinsics
PPTX
Story of static code analyzer development
PDF
maXbox Starter 39 GEO Maps Tutorial
PPTX
Accelerating Habanero-Java Program with OpenCL Generation
Best Bugs from Games: Fellow Programmers' Mistakes
Q4.11: Using GCC Auto-Vectorizer
Basic c++ 11/14 for python programmers
Fun with Lambdas: C++14 Style (part 1)
How to add an optimization for C# to RyuJIT
GPU Programming on CPU - Using C++AMP
HKG15-207: Advanced Toolchain Usage Part 3
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Fun with Lambdas: C++14 Style (part 2)
Arduino C maXbox web of things slide show
Summary of C++17 features
C++ 11 Features
To Swift 2...and Beyond!
Autovectorization in llvm
Bartosz Milewski, “Re-discovering Monads in C++”
Q4.11: NEON Intrinsics
Story of static code analyzer development
maXbox Starter 39 GEO Maps Tutorial
Accelerating Habanero-Java Program with OpenCL Generation
Ad

Viewers also liked (14)

PDF
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
PDF
Multithreading done right
PPT
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
PDF
High quality library from scratch
PDF
Debugging and Profiling C++ Template Metaprograms
PDF
Практика Lock-free. RealTime-сервер
PPTX
Асинхронность и сопрограммы
PPTX
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
PPT
Евгений Крутько, Многопоточные вычисления, современный подход.
PDF
С++ without new and delete
PDF
Конкурентные ассоциативные контейнеры
PDF
Использование юнит-тестов для повышения качества разработки
PDF
Parallel STL
PDF
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Multithreading done right
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
High quality library from scratch
Debugging and Profiling C++ Template Metaprograms
Практика Lock-free. RealTime-сервер
Асинхронность и сопрограммы
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Евгений Крутько, Многопоточные вычисления, современный подход.
С++ without new and delete
Конкурентные ассоциативные контейнеры
Использование юнит-тестов для повышения качества разработки
Parallel STL
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Ad

Similar to Конверсия управляемых языков в неуправляемые (20)

PDF
Introduction to typescript
PPT
Introduction to-csharp
PPT
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
PPT
Introduction-to-Csharp programacion orientada a objetos
PPT
Introduction-to-Csharp.ppt
PPT
Introduction-to-Csharp.ppt
PPT
IntroToCSharpcode.ppt
PDF
Introduction to c#
PDF
Introduction To Csharp
PDF
Tema3_Introduction_to_CUDA_C.pdf
PPT
Introduction to csharp
PPT
Introduction to csharp
PPT
Introduction to-csharp-1229579367461426-1
PPT
Introduction To Csharp
PPT
Introduction to csharp
PPS
Introduction to CSharp
PPTX
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
PPT
C#, What Is Next?
PPT
Introduction to csharp
PPT
Introduction to csharp
Introduction to typescript
Introduction to-csharp
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction-to-Csharp programacion orientada a objetos
Introduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
IntroToCSharpcode.ppt
Introduction to c#
Introduction To Csharp
Tema3_Introduction_to_CUDA_C.pdf
Introduction to csharp
Introduction to csharp
Introduction to-csharp-1229579367461426-1
Introduction To Csharp
Introduction to csharp
Introduction to CSharp
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
C#, What Is Next?
Introduction to csharp
Introduction to csharp

More from Platonov Sergey (20)

PPTX
Евгений Зуев, С++ в России: Стандарт языка и его реализация
PPTX
Алексей Кутумов, C++ без исключений, часть 3
PPTX
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
PDF
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
PDF
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
PDF
QML\Qt Quick на практике
PDF
Визуализация автомобильных маршрутов
PDF
Функциональный микроскоп: линзы в C++
PDF
C++ exceptions
PPTX
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
PDF
HPX: C++11 runtime система для параллельных и распределённых вычислений
PPTX
Ranges calendar-novosibirsk-2015-08
PDF
Использование maven для сборки больших модульных c++ проектов на примере Odin...
PDF
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
PDF
One definition rule - что это такое, и как с этим жить
PDF
DI в C++ тонкости и нюансы
PPTX
Аскетичная разработка браузера
PDF
Concepts lite
PDF
Денис Кормалев Метаобъектная система Qt
PDF
Максим Хижинский Lock-free maps
Евгений Зуев, С++ в России: Стандарт языка и его реализация
Алексей Кутумов, C++ без исключений, часть 3
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
QML\Qt Quick на практике
Визуализация автомобильных маршрутов
Функциональный микроскоп: линзы в C++
C++ exceptions
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
HPX: C++11 runtime система для параллельных и распределённых вычислений
Ranges calendar-novosibirsk-2015-08
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
One definition rule - что это такое, и как с этим жить
DI в C++ тонкости и нюансы
Аскетичная разработка браузера
Concepts lite
Денис Кормалев Метаобъектная система Qt
Максим Хижинский Lock-free maps

Конверсия управляемых языков в неуправляемые

  • 2. Managed language = C#, Java, D etc. GC (garbage collector), Unicode, … Unmanaged language Something that compiles to native code More control, less safety C/C++, VHDL, etc.
  • 3. Performance Stop-the-world GC Low-level control (e.g., SIMD) Collections (containers), multithreading Defense against reverse-engineering C#, Java are easy to decompile Hardware support CUDA, Xeon Phi Portability (surprise!) Sudden desire to write everything in С++
  • 4. Lex the source code Build AST Resolve symbols Traverse the tree, translating it to a different language Perfect translation is (of course) impossible
  • 5. Translate syntax with fidelity Fill the gaps in what’s missing Replace equivalent constructs List<>  vector<> Handle cases where 1-to-1 mapping is impossible
  • 6. Integral types Use types from <cstdint> int int32_t, byte  uint8_t, etc. float/double as-is Extended precision types (System.Decimal) Need external libs  Slightly different init rules
  • 7. Unicode  Most LoB apps do not absolutely require Unicode (nice to have) Relatively safe option: string  std::wstring char  wchar_t Slightly more careless option: string/char A completely safe solution has to allow strings to be nullptr I.e., you either use char* or option<string> Expensive, tedious, just use myString.empty() Unicode in source (identifiers, literals, …) won’t work
  • 8. class Person { string name; int age; } class Person { std::string name; int32_t age; public: Person(); };
  • 9. Managed languages Give types default values Allow initialization right in the declaration In both cases, initialization happens in the (generated) ctor In C++, types don’t have default values. So we are forced to make a constructor ourselves
  • 10. Property = field+getter+setter Can be read or write-only Can be automatic Name of field not specified explicitly Offers no benefit over a field in C++ Can have an inline initializer More ctor abuse  Two options here GetXxx/SetXxx (safe, tedious) __declspec(property) (not C++ standard, but nicer) int age; public int Age { get { return age; } set { age = value; } } // automatic public int Age { get; set; }
  • 11. __declspec(property(get = GetAge, put = PutAge)) int Age; int GetAge() const { return age; } void PutAge(int value) { … } // later Person p; p.Age = 123; // calls PutAge()
  • 12. Used in many places, e.g.: Handling UI interactions Property change notifications C++ doesn’t have them Boost.Signals Tricky since event subscription is done with += And unsubscription with −=
  • 13. template <typename T> class INotifyPropertyChanged { public: signal<void(const T*, string)> PropertyChanged; };
  • 14. class Player : public INotifyPropertyChanged<Player> { int age; public: __declspec(property(get = GetAge, put = PutAge)) int Age; int GetAge() const { return age; } void PutAge(int value) { if (value == age) return; PropertyChanged(this, "Age"); // oops, a string! (macro?) age = value; }
  • 15. “The big problem” GC  non-GC translation Store everything as shared_ptr Replace every `new` with make_shared Detecting use-cases for make_unique very difficult Circular references (weak_ptr<>?)
  • 16. References require#includes Need a list of typeheader for STL etc. Circular references may need forward declarations Header groupings (at namespace or folder level) Very tricky internal consistency (topological sort) Also a good idea for IDEs
  • 17. Type translation is (relatively) easy int  int32_t List<T>  vector<T> Function call translation is harder List.Add()  vector.emplace_back(), but… Value vs ref. stuff
  • 18. We need two converters One for .H files Another for .CPP files (implementation) The option of doing everything inline isn’t considered There are situations where 100% inlining doesn’t work
  • 20. Naming convention Clean Unicode handling Automated API mapping