--- title: "Accessing Native Code from a CLR UDF | Microsoft Docs" ms.custom: "" ms.date: "06/13/2017" ms.prod: "sql-server-2014" ms.reviewer: "" ms.technology: "database-engine" ms.topic: "reference" ms.assetid: 161afa9d-74a1-40f5-af17-162e355e7a46 author: mashamsft ms.author: mathoma manager: craigg --- # Accessing Native Code from a CLR UDF This example shows how to invoke a function in native (unmanaged) C++ code from a user-defined function in an assembly, in your database. For this example, the working directory should be `c:\test`. First compile the C++ code: ``` // Win32Sleep.cpp // compile with: /LD /link /noentry kernel32.lib #include extern "C" __declspec( dllexport ) void _cdecl SleepyLoop(DWORD sleep_interval) { Sleep(sleep_interval); } ``` Next, compile the C# code to an assembly: ``` // proc.cs // compile with: /target:library using System; using System.Threading; using System.Data.Sql; using System.Runtime.InteropServices; public class StoreProcedures { public static readonly uint SLEEP_LOOP_TIMES = 10; public static readonly uint SLEEP_DURATION = 1000; [DllImport(@"c:\test\Win32Sleep.dll")] internal static extern void SleepyLoop(uint sleepInterval); public static void SleepInProcedure(int loopTimes) { for ( int i = 0 ; i < loopTimes ; i++ ) { // invoke the unmanaged routine SleepyLoop(SLEEP_DURATION); } } } ``` Finally, execute the following [!INCLUDE[tsql](../../includes/tsql-md.md)]: ``` USE MASTER GO IF DB_ID('testdb') IS NOT NULL DROP DATABASE testdb GO CREATE DATABASE testdb GO USE testdb GO ALTER DATABASE testdb SET TRUSTWORTHY ON GO sp_configure 'show advanced options', 1 GO RECONFIGURE GO sp_configure 'clr enabled', 1 GO RECONFIGURE GO CREATE ASSEMBLY myasm FROM 'c:\test\proc.dll' WITH PERMISSION_SET=UNSAFE go CREATE PROCEDURE SleepProc(@loopTimes INT) AS EXTERNAL NAME myasm.[StoreProcedures].[SleepInProcedure] go -- sleep 5 seconds EXEC SleepProc 5 GO ``` ## See Also [Usage Scenarios and Examples for Common Language Runtime (CLR) Integration](../../../2014/database-engine/dev-guide/usage-scenarios-and-examples-for-common-language-runtime-clr-integration.md)