Native Plugins
Unity has extensive support for native Plugins, which are libraries of native code written in C, C++, Objective-C, etc. Plugins allow your game code (written in Javascript or C#) to call functions from these libraries. This feature allows Unity to integrate with middleware libraries or existing C/C++ game code.
Note: For security reasons, plugins are not usable in web player.
In order to use a native plugin you firstly need to write functions in a C-based language to access whatever features you need and compile them into a library. In Unity, you will also need to create a C# script which calls functions in the native library.
The native plugin should provide a simple C interface which the C# script then exposes to other user scripts. It is also possible for Unity to call functions exported by the native plugin when certain low-level rendering events happen (for example, when a graphics device is created), see the Native Plugin Interface page for details.
Пример
A very simple native library with a single function might have source code that looks like this:
float FooPluginFunction ()
To access this code from within Unity, you could use code like the following:
using UnityEngine; using System.Runtime.InteropServices; class SomeScript : MonoBehaviour < #if UNITY_IPHONE || UNITY_XBOX360 // On iOS and Xbox 360 plugins are statically linked into // the executable, so we have to use __Internal as the // library name. [DllImport ("__Internal")] #else // Other platforms load plugins dynamically, so pass the name // of the plugin's dynamic library. [DllImport ("PluginName")] #endif private static extern float FooPluginFunction (); void Awake () < // Calls the FooPluginFunction inside the plugin // And prints 5 to the console print (FooPluginFunction ()); >>
Обратите внимание, что при использовании Javascript вы должны будете использовать следующий синтаксис, где DLLName — это имя плагина, который вы написали, или “__Internal”, если вы пишете статически подключенный нативный код:
@DllImport (DLLName) static private function FooPluginFunction () : float <>;
Creating a Native Plugin
В основном, плагины собираются нативными компиляторами на целевой платформе. Так как функции плагинов используют интерфейс вызовов, основанный на C, вы должны избегать проблем с искажением имён при использовании C++ или Objective-C.
Further Information
- Native Plugin Interface — это необходимо, если вы хотите сделать рендеринг в вашем плагине.
- Mono Interop с нативными библиотеками.
- Документация по P-вызову на MSDN.
Как в JavaScript определить, является ли функция нативной
Время от времени мне приходится проверять, является ли та или иная функция нативной — это важная часть проверки, была ли функция предоставлена браузером или это порождение постороннего шима, замаскированное под встроенный компонент. Лучший способ выполнения такой проверки — это, конечно же, оценка значения toString , возвращённого функцией.
JavaScript
Код, требуемый для этого, довольно прост:
function isNative(fn) < return (/\/).test('' + fn); >
Вся суть состоит в том, чтобы конвертировать функцию в строчное представление и выполнить сопоставление строки с регулярными выражениями. Лучшего способа подтвердить, что это нативная функция, не существует!
Обновление!
Создатель библиотеки lodash, Джон-Дэвид Далтон (John-David Dalton), предложил лучшее решение:
;(function( ) < // Используется для разложения на составляющие внутреннего `[[Class]]` значений var toString = Object.prototype.toString; // Используется для разложения на составляющие декомпилированного // исходного кода функции var fnToString = Function.prototype.toString; // Используется для определения конструкторов среды (Safari > 4; // по сути, предназначено специально для типизированных массивов) var reHostCtor = /^\[object .+?Constructor\]$/; // Составление регулярного выражения на основе часто употребляемого // нативного метода в качестве шаблона. // Выбираем `Object#toString`, так как вполне вероятно, что он ещё не задействован. var reNative = RegExp('^' + // Применяем `Object#toString` к строке String(toString) // Избавляемся от любых специальных символов регулярных выражений .replace(/[.*+?^$<>()|[\]\/\\]/g, '\\$&') // Заменяем упоминания `toString` на `.*?`, чтобы сохранить обобщённый вид шаблона. // Заменяем `for . ` и тому подобное для поддержки окружений вроде Rhino, // которые добавляют дополнительную информацию, такую как арность метода. .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); function isNative(value) < var type = typeof value; return type == 'function' // Используем `Function#toString`, чтобы обойти собственный метод // `toString` самого значения и избежать ложного результата. ? reNative.test(fnToString.call(value)) // На всякий случай выполняем проверку на наличие объектов среды, так // как некоторые окружения могут представлять компоненты вроде // типизированных массивов как методы DOM, что может не соответствовать // нормальному нативному паттерну. : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false; > // экспортируем в удобном для вас виде module.exports = isNative; >());
И вот теперь у нас точно есть лучший подход для определения, является ли метод нативным. Естественно, не стоит использовать его для обеспечения безопасности — это лишь признак того, что функция нативна.
What does » [native code] » mean?
Possibly constructor method is inherited from JS object, which is part of basic browser functionality.
Jun 27, 2012 at 21:00
@gdoron It doesn’t answer the question directly, but jQuery is open source, so you can see for yourself what is in there.
Jun 27, 2012 at 21:00
Because that code is part of the V8 engine, which is implemented in C++ and therefore compiled code.
Jun 27, 2012 at 21:01
MDN source, for completeness
Apr 29, 2020 at 10:11
3 Answers 3
When you define functions in an interpreted language (as opposed to a compiled language). You have access to the file / string / text that defines the function.
In JavaScript for example you can read the definition body text of a function you have defined:
function custom( param ) < console.log( param ); >console.log( custom.toString() ); //
If you try to do the same for a function that is included by construction* in JavaScript it is not implemented as text but as binary.
console.log( setInterval.toString() ); // Will display: function setInterval()
There is no reason to show the binary code that implements that function because it is not readable and it might not even be available.
jQuery extends default JavaScript behaviour. It's one of the reasons it was so highly appreciated and praised as opposed to Prototype.js for example. Prototype was altering the natural behaviour of JavaScript creating possible inconsistencies when using Prototype alongside some other piece of code that relied on normal functionality.
tl;dr:
jQuery extends JavaScript, there is functionality implemented using native code (which performance wise is a good thing).
*included by construction: Elaborating a bit on this part. JavaScript itself can be written/implemented in any language (C++, Java, etc.). In Chrome, the JavaScript engine (V8) is written in C++. Firefox's JavaScript engine (SpiderMonkey) is also written in C++.
The functions that are defined by the language specification (ECMAScript) and should be included in the actual implementation, are written in another language (e.g. C++ in these 2 cases) and become available in JavaScript as built-in/native functions.
These functions are actually compiled (binary) C++ code and thus cannot be displayed within JavaScript itself, e.g. using the [].map.toString() syntax.
Почему пользовательская функция отображается как native code?

Почему пользовательская функция отображается как native code?
- Вопрос задан более трёх лет назад
- 2192 просмотра
10 комментариев
Простой 10 комментариев

Ярослав Иванов @space2pacman
потому что спрятали.
function lol() < return 10 >lol.toString = () => < return "f() < [native lolkek code] >" > console.log(lol) // ƒ f()
newaitix @newaitix Автор вопроса
Ярослав Иванов, Окей а как на счет этого?
Сюда можно нажать
И получим
А сюда нажимаю и ничего не получаю
Попробуйте сами
Яндекс карта на странице чекаут Авито доставка https://www.avito.ru/krasnodar/telefony/samsung_ga.

Ярослав Иванов @space2pacman
ymapsReady.toString ƒ ()

Ярослав Иванов @space2pacman